This file documents the Mathematical Graphic Library (MathGL), a collection of classes and routines for scientific plotting. It corresponds to release 2.4.3 of the library. Please report any errors in this manual to mathgl.abalakin@gmail.org. More information about MathGL can be found at the project homepage, http://mathgl.sourceforge.net/.
-
Permission is granted to copy, distribute and/or modify this document
-under the terms of the GNU Free Documentation License, Version 1.2
-or any later version published by the Free Software Foundation;
-with no Invariant Sections, no Front-Cover Texts, and no Back-Cover
-Texts. A copy of the license is included in the section entitled “GNU
-Free Documentation License.”
-
A code for making high-quality scientific graphics under Linux and Windows. A code for the fast handling and plotting of large data arrays. A code for working in window and console regimes and for easy including into another program. A code with large and renewal set of graphics. Exactly such a code I tried to put in MathGL library.
-
-
At this version (2.4.3) MathGL has more than 50 general types of graphics for 1d, 2d and 3d data arrays. It can export graphics to bitmap and vector (EPS or SVG) files. It has OpenGL interface and can be used from console programs. It has functions for data handling and script MGL language for simplification of data plotting. It also has several types of transparency and smoothed lighting, vector fonts and TeX-like symbol parsing, arbitrary curvilinear coordinate system and many other useful things (see pictures section at homepage). Finally it is platform-independent and free (under GPL v.2.0 or later license).
-
three-dimensional plots (Surf3, Dens3, Cont3, ContF3, Cloud-like, see 3D plotting);
-
-
dual data plots: vector fields Vect, flow threads Flow, mapping chart Map, surfaces and isosurfaces, transparent or colored (i.e. with transparency or color varied) by other data SurfA, SurfC, Surf3A, Surf3C (see Dual plotting);
-
-
In fact, I created the functions for drawing of all the types of scientific plots that I know. The list of plots is growing; if you need some special type of a plot then please email me e-mail and it will appear in the new version.
-
-
I tried to make plots as nice looking as possible: e.g., a surface can be transparent and highlighted by several (up to 10) light sources. Most of the drawing functions have 2 variants: simple one for the fast plotting of data, complex one for specifying of the exact position of the plot (including parametric representation). Resulting image can be saved in bitmap PNG, JPEG, GIF, TGA, BMP format, or in vector EPS, SVG or TeX format, or in 3D formats OBJ, OFF, STL, or in PRC format which can be converted into U3D.
-
-
All texts are drawn by vector fonts, which allows for high scalability and portability. Texts may contain commands for: some of the TeX-like symbols, changing index (upper or lower indexes) and the style of font inside the text string (see Font styles). Texts of ticks are rotated with axis rotation. It is possible to create a legend of plot and put text in an arbitrary position on the plot. Arbitrary text encoding (by the help of function setlocale()) and UTF-16 encoding are supported.
-
-
Special class mglData is used for data encapsulation (see Data processing). In addition to a safe creation and deletion of data arrays it includes functions for data processing (smoothing, differentiating, integrating, interpolating and so on) and reading of data files with automatic size determination. Class mglData can handle arrays with up to three dimensions (arrays which depend on up to 3 independent indexes a_{ijk}). Using an array with higher number of dimensions is not meaningful, because I do not know how it can be plotted. Data filling and modification may be done manually or by textual formulas.
-
-
There is fast evaluation of a textual mathematical expression (see Textual formulas). It is based on string precompilation to tree-like code at the creation of class instance. At evaluation stage code performs only fast tree-walk and returns the value of the expression. In addition to changing data values, textual formulas are also used for drawing in arbitrary curvilinear coordinates. A set of such curvilinear coordinates is limited only by user’s imagination rather than a fixed list like: polar, parabolic, spherical, and so on.
-
Compile from sources. The cmake build system is useded in the library. To run it, one should execute commands: cmake . twice, after it make and make install with root/sudo rights. Sometimes after installation you may need to update the library list – just execute ldconfig with root/sudo rights.
-
-
There are several additional options which are switched off by default. They are: enable-fltk, enable-glut, enable-qt4, enable-qt5 for ebabling FLTK, GLUT and/or Qt windows; enable-jpeg, enable-gif, enable-hdf5 and so on for enabling corresponding file formats; enable-all for enabling all additional features. For using double as base internal data type use option enable-double. For enabling language interfaces use enable-python, enable-octave or enable-all-swig for all languages. You can use WYSIWYG tool (cmake-gui) to view all of them, or type cmake -D enable-all=on -D enable-all-widgets=on -D enable-all-swig=on . in command line for enabling all features.
-
-
There is known bug for building in MinGW – you need to manually add linker option -fopenmp (i.e. CMAKE_EXE_LINKER_FLAGS:STRING='-fopenmp' and CMAKE_SHARED_LINKER_FLAGS:STRING='-fopenmp') if you enable OpenMP support (i.e. if enable-openmp=ON).
-
-
Use a precompiled binary. There are binaries for MinGW (platform Win32). For a precompiled variant one needs only to unpack the archive to the location of the compiler (i.e. mathgl/lib in mingw/lib, mathgl/include in mingw/include and so on) or in arbitrary other folder and setup paths in compiler. By default, precompiled versions include the support of GSL (www.gsl.org) and PNG. So, one needs to have these libraries installed on system (it can be found, for example, at http://gnuwin32.sourceforge.net/packages.html).
-
-
Install precompiled versions from standard packages (RPM, deb, DevPak and so on).
-
-
-
Note, you can download the latest sources (which can be not stable) from sourceforge.net SVN by command
-
IMPORTANT! MathGL use a set of defines, which were determined at configure stage and may differ if used with non-default compiler (like using MathGL binaries compiled by MinGW in VisualStudio). There are MGL_SYS_NAN, MGL_HAVE_TYPEOF, MGL_HAVE_PTHREAD, MGL_HAVE_ATTRIBUTE, MGL_HAVE_C99_COMPLEX, MGL_HAVE_RVAL. I specially set them to 0 for Borland and Microsoft compilers due to compatibility reasons. Also default setting are good for GNU (gcc, mingw) and clang compilers. However, for another compiler you may need to manually set this defines to 0 in file include/mgl2/config.h if you are using precompiled binaries.
-
There are 3 steps to prepare the plot in MathGL: (1) prepare data to be plotted, (2) setup plot, (3) plot data. Let me show this on the example of surface plotting.
-
-
First we need the data. MathGL use its own class mglData to handle data arrays (see Data processing). This class give ability to handle data arrays by more or less format independent way. So, create it
-
int main()
- {
- mglData dat(30,40); // data to for plotting
- for(long i=0;i<30;i++) for(long j=0;j<40;j++)
- dat.a[i+30*j] = 1/(1+(i-15)*(i-15)/225.+(j-20)*(j-20)/400.);
-
Here I create matrix 30*40 and initialize it by formula. Note, that I use long type for indexes i, j because data arrays can be really large and long type will automatically provide proper indexing.
-
-
Next step is setup of the plot. The only setup I need is axis rotation and lighting.
-
mglGraph gr; // class for plot drawing
- gr.Rotate(50,60); // rotate axis
- gr.Light(true); // enable lighting
-
-
Everything is ready. And surface can be plotted.
-
gr.Surf(dat); // plot surface
-
Basically plot is done. But I decide to add yellow (‘y’ color, see Color styles) contour lines on the surface. To do it I can just add:
-
gr.Cont(dat,"y"); // plot yellow contour lines
-
This demonstrate one of base MathGL concept (see, General concepts) – “new drawing never clears things drawn already”. So, you can just consequently call different plotting functions to obtain “combined” plot. For example, if one need to draw axis then he can just call one more plotting function
-
gr.Axis(); // draw axis
-
-
Now picture is ready and we can save it in a file.
-
gr.WriteFrame("sample.png"); // save it
- }
-
-
To compile your program, you need to specify the linker option -lmgl.
-
-
This is enough for a compilation of console program or with external (non-MathGL) window library. If you want to use FLTK or Qt windows provided by MathGL then you need to add the option -lmgl-wnd.
-
-
Fortran users also should add C++ library by the option -lstdc++. If library was built with enable-double=ON (this default for v.2.1 and later) then all real numbers must be real*8. You can make it automatic if use option -fdefault-real-8.
-
MathGL library provides several tools for parsing MGL scripts. There is tools saving it to bitmap or vectorial images (mglconv). Tool mglview show MGL script and allow to rotate and setup the image. Another feature of mglview is loading *.mgld files (see ExportMGLD()) for quick viewing 3d pictures.
-
-
Both tools have similar set of arguments. They can be name of script file or options. You can use ‘-’ as script name for using standard input (i.e. pipes). Options are:
-
-
-1str
-set str as argument $1 for script;
-
...
-...
-
-9str
-set str as argument $9 for script;
-
-Lloc
-set locale to loc;
-
-sfname
-set MGL script for setting up the plot;
-
-h
-print help message.
-
-
Additionally mglconv have following options:
-
-
-Aval
-add val into the list of animation parameters;
-
-Cv1:v2[:dv]
-add values from v1 ot v2 with step dv (default is 1) into the list of animation parameters;
-
-oname
-set output file name;
-
-n
-disable default output (script should save results by itself);
-
Also you can create animated GIF file or a set of JPEG files with names ‘frameNNNN.jpg’ (here ‘NNNN’ is frame index). Values of the parameter $0 for making animation can be specified inside the script by comment ##a val for each value val (one comment for one value) or by option(s) ‘-A val’. Also you can specify a cycle for animation by comment ##c v1 v2 dv or by option -C v1:v2:dv. In the case of found/specified animation parameters, tool will execute script several times – once for each value of $0.
-
-
-
MathGL also provide another simple tool mgl.cgi which parse MGL script from CGI request and send back produced PNG file. Usually this program should be placed in /usr/lib/cgi-bin/. But you need to put this program by yourself due to possible security issues and difference of Apache server settings.
-
My special thanks to my wife for the patience during the writing of this library and for the help in documentation writing and spelling.
-
I’m thankful to my coauthors D. Kulagin and M. Vidassov for help in developing MathGL.
-
I’m thankful to Diego Sejas Viscarra for developing mgltex, contribution to fractal generation and fruitful suggestions.
-
I’m thankful to D. Eftaxiopoulos, D. Haley, V. Lipatov and S.M. Plis for making binary packages for Linux.
-
I’m thankful to S. Skobelev, C. Mikhailenko, M. Veysman, A. Prokhorov, A. Korotkevich, V. Onuchin, S.M. Plis, R. Kiselev, A. Ivanov, N. Troickiy and V. Lipatov for fruitful comments.
-
I’m thankful to sponsors M. Veysman (IHED RAS) and A. Prokhorov (DATADVANCE).
-
-
-
Javascript interface was developed with support of DATADVANCE company.
-
This chapter contain information about basic and advanced MathGL, hints and samples for all types of graphics. I recommend you read first 2 sections one after another and at least look on Hints section. Also I recommend you to look at General concepts and FAQ.
-
-
Note, that MathGL v.2.* have only 2 end-user interfaces: one for C/Fortran and similar languages which don’t support classes, another one for C++/Python/Octave and similar languages which support classes. So, most of samples placed in this chapter can be run as is (after minor changes due to different syntaxes for different languages). For example, the C++ code
-
MathGL library can be used by several manners. Each has positive and negative sides:
-
-
Using of MathGL library features for creating graphical window (requires FLTK, Qt or GLUT libraries).
-
-
Positive side is the possibility to view the plot at once and to modify it (rotate, zoom or switch on transparency or lighting) by hand or by mouse. Negative sides are: the need of X-terminal and limitation consisting in working with the only one set of data at a time.
-
-
Direct writing to file in bitmap or vector format without creation of graphical window.
-
-
Positive aspects are: batch processing of similar data set (for example, a set of resulting data files for different calculation parameters), running from the console program (including the cluster calculation), fast and automated drawing, saving pictures for further analysis (or demonstration). Negative sides are: the usage of the external program for picture viewing. Also, the data plotting is non-visual. So, you have to imagine the picture (view angles, lighting and so on) before the plotting. I recommend to use graphical window for determining the optimal parameters of plotting on the base of some typical data set. And later use these parameters for batch processing in console program.
-
-
Drawing in memory with the following displaying by other graphical program.
-
-
In this case the programmer has more freedom in selecting the window libraries (not only FLTK, Qt or GLUT), in positioning and surroundings control and so on. I recommend to use such way for “stand alone” programs.
-
-
Using FLTK or Qt widgets provided by MathGL
-
-
Here one can use a set of standard widgets which support export to many file formats, copying to clipboard, handle mouse and so on.
-
-
-
MathGL drawing can be created not only by object oriented languages (like, C++ or Python), but also by pure C or Fortran-like languages. The usage of last one is mostly identical to usage of classes (except the different function names). But there are some differences. C functions must have argument HMGL (for graphics) and/or HMDT (for data arrays) which specifies the object for drawing or manipulating (changing). Fortran users may regard these variables as integer. So, firstly the user has to create this object by function mgl_create_*() and has to delete it after the using by function mgl_delete_*().
-
The “interactive” way of drawing in MathGL consists in window creation with help of class mglQT, mglFLTK or mglGLUT (see Widget classes) and the following drawing in this window. There is a corresponding code:
-
Here callback function sample is defined. This function does all drawing. Other function main is entry point function for console program. For compilation, just execute the command
-
gcc test.cpp -lmgl-qt5 -lmgl
-
You can use "-lmgl-qt4" instead of "-lmgl-qt5", if Qt4 is installed.
-
-
Alternatively you can create yours own class inherited from mglDraw class and re-implement the function Draw() in it:
-
The rotation, shift, zooming, switching on/off transparency and lighting can be done with help of tool-buttons (for mglQT, mglFLTK) or by hot-keys: ‘a’, ‘d’, ‘w’, ‘s’ for plot rotation, ‘r’ and ‘f’ switching on/off transparency and lighting. Press ‘x’ for exit (or closing the window).
-
-
In this example function sample rotates axes (Rotate(), see Subplots and rotation) and draws the bounding box (Box()). Drawing is placed in separate function since it will be used on demand when window canvas needs to be redrawn.
-
Another way of using MathGL library is the direct writing of the picture to the file. It is most usable for plot creation during long calculation or for using of small programs (like Matlab or Scilab scripts) for visualizing repetitive sets of data. But the speed of drawing is much higher in comparison with a script language.
-
-
The following code produces a bitmap PNG picture:
-
#include <mgl2/mgl.h>
-int main(int ,char **)
-{
- mglGraph gr;
- gr.Alpha(true); gr.Light(true);
- sample(&gr); // The same drawing function.
- gr.WritePNG("test.png"); // Don't forget to save the result!
- return 0;
-}
-
For compilation, you need only libmgl library not the one with widgets
-
gcc test.cpp -lmgl
-
This can be important if you create a console program in computer/cluster where X-server (and widgets) is inaccessible.
-
-
The only difference from the previous variant (using windows) is manual switching on the transparency Alpha and lightning Light, if you need it. The usage of frames (see Animation) is not advisable since the whole image is prepared each time. If function sample contains frames then only last one will be saved to the file. In principle, one does not need to separate drawing functions in case of direct file writing in consequence of the single calling of this function for each picture. However, one may use the same drawing procedure to create a plot with changeable parameters, to export in different file types, to emphasize the drawing code and so on. So, in future I will put the drawing in the separate function.
-
-
The code for export into other formats (for example, into vector EPS file) looks the same:
-
#include <mgl2/mgl.h>
-int main(int ,char **)
-{
- mglGraph gr;
- gr.Light(true);
- sample(&gr); // The same drawing function.
- gr.WriteEPS("test.eps"); // Don't forget to save the result!
- return 0;
-}
-
The difference from the previous one is using other function WriteEPS() for EPS format instead of function WritePNG(). Also, there is no switching on of the plot transparency Alpha since EPS format does not support it.
-
Widget classes (mglWindow, mglGLUT) support a delayed drawing, when all plotting functions are called once at the beginning of writing to memory lists. Further program displays the saved lists faster. Resulting redrawing will be faster but it requires sufficient memory. Several lists (frames) can be displayed one after another (by pressing ‘,’, ‘.’) or run as cinema. To switch these feature on one needs to modify function sample:
-
int sample(mglGraph *gr)
-{
- gr->NewFrame(); // the first frame
- gr->Rotate(60,40);
- gr->Box();
- gr->EndFrame(); // end of the first frame
- gr->NewFrame(); // the second frame
- gr->Box();
- gr->Axis("xy");
- gr->EndFrame(); // end of the second frame
- return gr->GetNumFrame(); // returns the frame number
-}
-
First, the function creates a frame by calling NewFrame() for rotated axes and draws the bounding box. The function EndFrame()must be called after the frame drawing! The second frame contains the bounding box and axes Axis("xy") in the initial (unrotated) coordinates. Function sample returns the number of created frames GetNumFrame().
-
-
Note, that animation can be also done as visualization of running calculations (see Draw and calculate).
-
-
Pictures with animation can be saved in file(s) as well. You can: export in animated GIF, or save each frame in separate file (usually JPEG) and convert these files into the movie (for example, by help of ImageMagic). Let me show both methods.
-
-
The simplest methods is making animated GIF. There are 3 steps: (1) open GIF file by StartGIF() function; (2) create the frames by calling NewFrame() before and EndFrame() after plotting; (3) close GIF by CloseGIF() function. So the simplest code for “running” sinusoid will look like this:
-
The second way is saving each frame in separate file (usually JPEG) and later make the movie from them. MathGL have special function for saving frames – it is WriteFrame(). This function save each frame with automatic name ‘frame0001.jpg, frame0002.jpg’ and so on. Here prefix ‘frame’ is defined by PlotId variable of mglGraph class. So the similar code will look like this:
-
Created files can be converted to movie by help of a lot of programs. For example, you can use ImageMagic (command ‘convert frame*.jpg movie.mpg’), MPEG library, GIMP and so on.
-
-
Finally, you can use mglconv tool for doing the same with MGL scripts (see Utilities).
-
The last way of MathGL using is the drawing in memory. Class mglGraph allows one to create a bitmap picture in memory. Further this picture can be displayed in window by some window libraries (like wxWidgets, FLTK, Windows GDI and so on). For example, the code for drawing in wxWidget library looks like:
-
void MyForm::OnPaint(wxPaintEvent& event)
-{
- int w,h,x,y;
- GetClientSize(&w,&h); // size of the picture
- mglGraph gr(w,h);
-
- gr.Alpha(true); // draws something using MathGL
- gr.Light(true);
- sample(&gr,NULL);
-
- wxImage img(w,h,gr.GetRGB(),true);
- ToolBar->GetSize(&x,&y); // gets a height of the toolbar if any
- wxPaintDC dc(this); // and draws it
- dc.DrawBitmap(wxBitmap(img),0,y);
-}
-
The drawing in other libraries is most the same.
-
MathGL can be used to draw plots in parallel with some external calculations. The simplest way for this is the usage of mglDraw class. At this you should enable pthread for widgets by setting enable-pthr-widget=ON at configure stage (it is set by default).
-First, you need to inherit you class from mglDraw class, define virtual members Draw() and Calc() which will draw the plot and proceed calculations. You may want to add the pointer mglWnd *wnd; to window with plot for interacting with them. Finally, you may add any other data or member functions. The sample class is shown below
-
class myDraw : public mglDraw
-{
- mglPoint pnt; // some variable for changeable data
- long i; // another variable to be shown
- mglWnd *wnd; // external window for plotting
-public:
- myDraw(mglWnd *w=0) : mglDraw() { wnd=w; }
- void SetWnd(mglWnd *w) { wnd=w; }
- int Draw(mglGraph *gr)
- {
- gr->Line(mglPoint(),pnt,"Ar2");
- char str[16]; snprintf(str,15,"i=%ld",i);
- gr->Puts(mglPoint(),str);
- return 0;
- }
- void Calc()
- {
- for(i=0;;i++) // do calculation
- {
- long_calculations();// which can be very long
- Check(); // check if need pause
- pnt.Set(2*mgl_rnd()-1,2*mgl_rnd()-1);
- if(wnd) wnd->Update();
- }
- }
-} dr;
-
There is only one issue here. Sometimes you may want to pause calculations to view result carefully, or save state, or change something. So, you need to provide a mechanism for pausing. Class mglDraw provide function Check(); which check if toolbutton with pause is pressed and wait until it will be released. This function should be called in a "safety" places, where you can pause the calculation (for example, at the end of time step). Also you may add call exit(0); at the end of Calc(); function for closing window and exit after finishing calculations.
-Finally, you need to create a window itself and run calculations.
-
int main(int argc,char **argv)
-{
- mglFLTK gr(&dr,"Multi-threading test"); // create window
- dr.SetWnd(&gr); // pass window pointer to yours class
- dr.Run(); // run calculations
- gr.Run(); // run event loop for window
- return 0;
-}
-
-
Note, that you can reach the similar functionality without using mglDraw class (i.e. even for pure C code).
-
mglFLTK *gr=NULL; // pointer to window
-void *calc(void *) // function with calculations
-{
- mglPoint pnt; // some data for plot
- for(long i=0;;i++) // do calculation
- {
- long_calculations(); // which can be very long
- pnt.Set(2*mgl_rnd()-1,2*mgl_rnd()-1);
- if(gr)
- {
- gr->Clf(); // make new drawing
- // draw something
- gr->Line(mglPoint(),pnt,"Ar2");
- char str[16]; snprintf(str,15,"i=%ld",i);
- gr->Puts(mglPoint(),str);
- // don't forgot to update window
- gr->Update();
- }
- }
-}
-int main(int argc,char **argv)
-{
- static pthread_t thr;
- pthread_create(&thr,0,calc,0); // create separate thread for calculations
- pthread_detach(thr); // and detach it
- gr = new mglFLTK; // now create window
- gr->Run(); // and run event loop
- return 0;
-}
-
This sample is exactly the same as one with mglDraw class, but it don’t have functionality for pausing calculations. If you need it then you have to create global mutex (like pthread_mutex_t *mutex = pthread_mutex_init(&mutex,NULL);), set it to window (like gr->SetMutex(mutex);) and periodically check it at calculations (like pthread_mutex_lock(&mutex); pthread_mutex_unlock(&mutex);).
-
-
Finally, you can put the event-handling loop in separate instead of yours code by using RunThr() function instead of Run() one. Unfortunately, such method work well only for FLTK windows and only if pthread support was enabled. Such limitation come from the Qt requirement to be run in the primary thread only. The sample code will be:
-
int main(int argc,char **argv)
-{
- mglFLTK gr("test");
- gr.RunThr(); // <-- need MathGL version which use pthread for widgets
- mglPoint pnt; // some data
- for(int i=0;i<10;i++) // do calculation
- {
- long_calculations();// which can be very long
- pnt.Set(2*mgl_rnd()-1,2*mgl_rnd()-1);
- gr.Clf(); // make new drawing
- gr.Line(mglPoint(),pnt,"Ar2");
- char str[10] = "i=0"; str[3] = '0'+i;
- gr->Puts(mglPoint(),str);
- gr.Update(); // update window
- }
- return 0; // finish calculations and close the window
-}
-
MathGL have several interface widgets for different widget libraries. There are QMathGL for Qt, Fl_MathGL for FLTK. These classes provide control which display MathGL graphics. Unfortunately there is no uniform interface for widget classes because all libraries have slightly different set of functions, features and so on. However the usage of MathGL widgets is rather simple. Let me show it on the example of QMathGL.
-
-
First of all you have to define the drawing function or inherit a class from mglDraw class. After it just create a window and setup QMathGL instance as any other Qt widget:
-
#include <QApplication>
-#include <QMainWindow>
-#include <QScrollArea>
-#include <mgl2/qmathgl.h>
-int main(int argc,char **argv)
-{
- QApplication a(argc,argv);
- QMainWindow *Wnd = new QMainWindow;
- Wnd->resize(810,610); // for fill up the QMGL, menu and toolbars
- Wnd->setWindowTitle("QMathGL sample");
- // here I allow to scroll QMathGL -- the case
- // then user want to prepare huge picture
- QScrollArea *scroll = new QScrollArea(Wnd);
-
- // Create and setup QMathGL
- QMathGL *QMGL = new QMathGL(Wnd);
-//QMGL->setPopup(popup); // if you want to setup popup menu for QMGL
- QMGL->setDraw(sample);
- // or use QMGL->setDraw(foo); for instance of class Foo:public mglDraw
- QMGL->update();
-
- // continue other setup (menu, toolbar and so on)
- scroll->setWidget(QMGL);
- Wnd->setCentralWidget(scroll);
- Wnd->show();
- return a.exec();
-}
-
MathGL have possibility to draw resulting plot using OpenGL. This produce resulting plot a bit faster, but with some limitations (especially at use of transparency and lighting). Generally, you need to prepare OpenGL window and call MathGL functions to draw it. There is GLUT interface (see Widget classes) to do it by simple way. Below I show example of OpenGL usage basing on Qt libraries (i.e. by using QGLWidget widget).
-
-
First, one need to define widget class derived from QGLWidget and implement a few methods: resizeGL() called after each window resize, paintGL() for displaying the image on the screen, and initializeGL() for initializing OpenGL. The header file looks as following.
-
#ifndef MAINWINDOW_H
-#define MAINWINDOW_H
-
-#include <QGLWidget>
-#include <mgl2/mgl.h>
-
-class MainWindow : public QGLWidget
-{
- Q_OBJECT
-protected:
- mglGraph *gr; // pointer to MathGL core class
- void resizeGL(int nWidth, int nHeight); // Method called after each window resize
- void paintGL(); // Method to display the image on the screen
- void initializeGL(); // Method to initialize OpenGL
-public:
- MainWindow(QWidget *parent = 0);
- ~MainWindow();
-};
-#endif // MAINWINDOW_H
-
-
The class implementation is rather straightforward. One need to recreate the instance of mglGraph at initializing OpenGL, and ask MathGL to use OpenGL output (set argument 1 in mglGraph constructor). Of course, the mglGraph object should be deleted at destruction. The method resizeGL() just pass new sizes to OpenGL and update viewport sizes. All plotting functions are located in the method paintGL(). At this, one need to add 2 calls: gr->Clf() at beginning for clearing previous OpenGL primitives; and swapBuffers() for showing output on the screen. The source file looks as following.
-
#include "qgl_example.h"
-#include <QApplication>
-//#include <QtOpenGL>
-//-----------------------------------------------------------------------------
-MainWindow::MainWindow(QWidget *parent) : QGLWidget(parent) { gr=0; }
-//-----------------------------------------------------------------------------
-MainWindow::~MainWindow() { if(gr) delete gr; }
-//-----------------------------------------------------------------------------
-void MainWindow::initializeGL() // recreate instance of MathGL core
-{
- if(gr) delete gr;
- gr = new mglGraph(1); // use '1' for argument to force OpenGL output in MathGL
-}
-//-----------------------------------------------------------------------------
-void MainWindow::resizeGL(int w, int h) // standard resize replace
-{
- QGLWidget::resizeGL(w, h);
- glViewport (0, 0, w, h);
-}
-//-----------------------------------------------------------------------------
-void MainWindow::paintGL() // main drawing function
-{
- gr->Clf(); // clear previous OpenGL primitives
- gr->SubPlot(1,1,0);
- gr->Rotate(40,60);
- gr->Light(true);
- gr->AddLight(0,mglPoint(0,0,10),mglPoint(0,0,-1));
- gr->Axis();
- gr->Box();
- gr->FPlot("sin(pi*x)","i2");
- gr->FPlot("cos(pi*x)","|");
- gr->FSurf("cos(2*pi*(x^2+y^2))");
- gr->Finish();
- swapBuffers(); // show output on the screen
-}
-//-----------------------------------------------------------------------------
-int main(int argc, char *argv[]) // create application
-{
- mgl_textdomain(argv?argv[0]:NULL,"");
- QApplication a(argc, argv);
- MainWindow w;
- w.show();
- return a.exec();
-}
-//-----------------------------------------------------------------------------
-
Generally SWIG based classes (including the Python one) are the same as C++ classes. However, there are few tips for using MathGL with PyQt. Below I place a very simple python code which demonstrate how MathGL can be used with PyQt. This code is mostly written by Prof. Dr. Heino Falcke. You can just copy it to a file mgl-pyqt-test.py and execute it from python shell by command execfile("mgl-pyqt-test.py")
-
For using MathGL in MPI program you just need to: (1) plot its own part of data for each running node; (2) collect resulting graphical information in a single program (for example, at node with rank=0); (3) save it. The sample code below demonstrate this for very simple sample of surface drawing.
-
Next step is data creation. For simplicity, I create data arrays with the same sizes for all nodes. At this, you have to create mglGraph object too.
-
-
// initialize data similarly for all nodes
- mglData a(128,256);
- mglGraphMPI gr;
-
-
Now, data should be filled by numbers. In real case, it should be some kind of calculations. But I just fill it by formula.
-
-
// do the same plot for its own range
- char buf[64];
- sprintf(buf,"xrange %g %g",2.*rank/numproc-1,2.*(rank+1)/numproc-1);
- gr.Fill(a,"sin(2*pi*x)",buf);
-
-
It is time to plot the data. Don’t forget to set proper axis range(s) by using parametric form or by using options (as in the sample).
-
-
// plot data in each node
- gr.Clf(); // clear image before making the image
- gr.Rotate(40,60);
- gr.Surf(a,"",buf);
-
-
Finally, let send graphical information to node with rank=0.
-
Now, node with rank=0 have whole image. It is time to save the image to a file. Also, you can add a kind of annotations here – I draw axis and bounding box in the sample.
-
-
if(rank==0)
- {
- gr.Box(); gr.Axis(); // some post processing
- gr.WritePNG("test.png"); // save result
- }
-
-
In my case the program is done, and I finalize MPI. In real program, you can repeat the loop of data calculation and data plotting as many times as you need.
-
-
MPI_Finalize();
- return 0;
-}
-
-
You can type ‘mpic++ test.cpp -lmgl-mpi -lmgl && mpirun -np 8 ./a.out’ for compilation and running the sample program on 8 nodes. Note, that you have to set enable-mpi=ON at MathGL configure to use this feature.
-
Now I show several non-obvious features of MathGL: several subplots in a single picture, curvilinear coordinates, text printing and so on. Generally you may miss this section at first reading.
-
Let me demonstrate possibilities of plot positioning and rotation. MathGL has a set of functions: subplot, inplot, title, aspect and rotate and so on (see Subplots and rotation). The order of their calling is strictly determined. First, one changes the position of plot in image area (functions subplot, inplot and multiplot). Secondly, you can add the title of plot by title function. After that one may rotate the plot (function rotate). Finally, one may change aspects of axes (function aspect). The following code illustrates the aforesaid it:
-
Here I used function Puts for printing the text in arbitrary position of picture (see Text printing). Text coordinates and size are connected with axes. However, text coordinates may be everywhere, including the outside the bounding box. I’ll show its features later in Text features.
-
-
-
-
More complicated sample show how to use most of positioning functions:
-
MathGL library can draw not only the bounding box but also the axes, grids, labels and so on. The ranges of axes and their origin (the point of intersection) are determined by functions SetRange(), SetRanges(), SetOrigin() (see Ranges (bounding box)). Ticks on axis are specified by function SetTicks, SetTicksVal, SetTicksTime (see Ticks). But usually
-
-
Function axis draws axes. Its textual string shows in which directions the axis or axes will be drawn (by default "xyz", function draws axes in all directions). Function grid draws grid perpendicularly to specified directions. Example of axes and grid drawing is:
-
Note, that MathGL can draw not only single axis (which is default). But also several axis on the plot (see right plots). The idea is that the change of settings does not influence on the already drawn graphics. So, for 2-axes I setup the first axis and draw everything concerning it. Then I setup the second axis and draw things for the second axis. Generally, the similar idea allows one to draw rather complicated plot of 4 axis with different ranges (see bottom left plot).
-
-
At this inverted axis can be created by 2 methods. First one is used in this sample – just specify minimal axis value to be large than maximal one. This method work well for 2D axis, but can wrongly place labels in 3D case. Second method is more general and work in 3D case too – just use aspect function with negative arguments. For example, following code will produce exactly the same result for 2D case, but 2nd variant will look better in 3D.
-
Another MathGL feature is fine ticks tunning. By default (if it is not changed by SetTicks function), MathGL try to adjust ticks positioning, so that they looks most human readable. At this, MathGL try to extract common factor for too large or too small axis ranges, as well as for too narrow ranges. Last one is non-common notation and can be disabled by SetTuneTicks function.
-
-
Also, one can specify its own ticks with arbitrary labels by help of SetTicksVal function. Or one can set ticks in time format. In last case MathGL will try to select optimal format for labels with automatic switching between years, months/days, hours/minutes/seconds or microseconds. However, you can specify its own time representation using formats described in http://www.manpagez.com/man/3/strftime/. Most common variants are ‘%X’ for national representation of time, ‘%x’ for national representation of date, ‘%Y’ for year with century.
-
-
The sample code, demonstrated ticks feature is
-
int sample(mglGraph *gr)
-{
- gr->SubPlot(3,3,0); gr->Title("Usual axis"); gr->Axis();
- gr->SubPlot(3,3,1); gr->Title("Too big/small range");
- gr->SetRanges(-1000,1000,0,0.001); gr->Axis();
- gr->SubPlot(3,3,2); gr->Title("LaTeX-like labels");
- gr->Axis("F!");
- gr->SubPlot(3,3,3); gr->Title("Too narrow range");
- gr->SetRanges(100,100.1,10,10.01); gr->Axis();
- gr->SubPlot(3,3,4); gr->Title("No tuning, manual '+'");
- // for version<2.3 you need first call gr->SetTuneTicks(0);
- gr->Axis("+!");
- gr->SubPlot(3,3,5); gr->Title("Template for ticks");
- gr->SetTickTempl('x',"xxx:%g"); gr->SetTickTempl('y',"y:%g");
- gr->Axis();
- // now switch it off for other plots
- gr->SetTickTempl('x',""); gr->SetTickTempl('y',"");
- gr->SubPlot(3,3,6); gr->Title("No tuning, higher precision");
- gr->Axis("!4");
- gr->SubPlot(3,3,7); gr->Title("Manual ticks"); gr->SetRanges(-M_PI,M_PI, 0, 2);
- gr->SetTicks('x',M_PI,0,0,"\\pi"); gr->AddTick('x',0.886,"x^*");
- // alternatively you can use following lines
- //double val[]={-M_PI, -M_PI/2, 0, 0.886, M_PI/2, M_PI};
- //gr->SetTicksVal('x', mglData(6,val), "-\\pi\n-\\pi/2\n0\nx^*\n\\pi/2\n\\pi");
- gr->Axis(); gr->Grid(); gr->FPlot("2*cos(x^2)^2", "r2");
- gr->SubPlot(3,3,8); gr->Title("Time ticks"); gr->SetRange('x',0,3e5);
- gr->SetTicksTime('x',0); gr->Axis();
-}
-
-
-
-
The last sample I want to show in this subsection is Log-axis. From MathGL’s point of view, the log-axis is particular case of general curvilinear coordinates. So, we need first define new coordinates (see also Curvilinear coordinates) by help of SetFunc or SetCoor functions. At this one should wary about proper axis range. So the code looks as following:
-
You can see that MathGL automatically switch to log-ticks as we define log-axis formula (in difference from v.1.*). Moreover, it switch to log-ticks for any formula if axis range will be large enough (see right bottom plot). Another interesting feature is that you not necessary define usual log-axis (i.e. when coordinates are positive), but you can define “minus-log” axis when coordinate is negative (see left bottom plot).
-
As I noted in previous subsection, MathGL support curvilinear coordinates. In difference from other plotting programs and libraries, MathGL uses textual formulas for connection of the old (data) and new (output) coordinates. This allows one to plot in arbitrary coordinates. The following code plots the line y=0, z=0 in Cartesian, polar, parabolic and spiral coordinates:
-
MathGL handle colorbar as special kind of axis. So, most of functions for axis and ticks setup will work for colorbar too. Colorbars can be in log-scale, and generally as arbitrary function scale; common factor of colorbar labels can be separated; and so on.
-
-
But of course, there are differences – colorbars usually located out of bounding box. At this, colorbars can be at subplot boundaries (by default), or at bounding box (if symbol ‘I’ is specified). Colorbars can handle sharp colors. And they can be located at arbitrary position too. The sample code, which demonstrate colorbar features is:
-
Box around the plot is rather useful thing because it allows one to: see the plot boundaries, and better estimate points position since box contain another set of ticks. MathGL provide special function for drawing such box – box function. By default, it draw black or white box with ticks (color depend on transparency type, see Types of transparency). However, you can change the color of box, or add drawing of rectangles at rear faces of box. Also you can disable ticks drawing, but I don’t know why anybody will want it. The sample code, which demonstrate box features is:
-
There are another unusual axis types which are supported by MathGL. These are ternary and quaternary axis. Ternary axis is special axis of 3 coordinates a, b, c which satisfy relation a+b+c=1. Correspondingly, quaternary axis is special axis of 4 coordinates a, b, c, d which satisfy relation a+b+c+d=1.
-
-
Generally speaking, only 2 of coordinates (3 for quaternary) are independent. So, MathGL just introduce some special transformation formulas which treat a as ‘x’, b as ‘y’ (and c as ‘z’ for quaternary). As result, all plotting functions (curves, surfaces, contours and so on) work as usual, but in new axis. You should use ternary function for switching to ternary/quaternary coordinates. The sample code is:
-
MathGL prints text by vector font. There are functions for manual specifying of text position (like Puts) and for its automatic selection (like Label, Legend and so on). MathGL prints text always in specified position even if it lies outside the bounding box. The default size of font is specified by functions SetFontSize* (see Font settings). However, the actual size of output string depends on subplot size (depends on functions SubPlot, InPlot). The switching of the font style (italic, bold, wire and so on) can be done for the whole string (by function parameter) or inside the string. By default MathGL parses TeX-like commands for symbols and indexes (see Font styles).
-
-
Text can be printed as usual one (from left to right), along some direction (rotated text), or along a curve. Text can be printed on several lines, divided by new line symbol ‘\n’.
-
-
Example of MathGL font drawing is:
-
int sample(mglGraph *gr)
-{
- gr->SubPlot(2,2,0,"");
- gr->Putsw(mglPoint(0,1),L"Text can be in ASCII and in Unicode");
- gr->Puts(mglPoint(0,0.6),"It can be \\wire{wire}, \\big{big} or #r{colored}");
- gr->Puts(mglPoint(0,0.2),"One can change style in string: "
- "\\b{bold}, \\i{italic, \\b{both}}");
- gr->Puts(mglPoint(0,-0.2),"Easy to \\a{overline} or "
- "\\u{underline}");
- gr->Puts(mglPoint(0,-0.6),"Easy to change indexes ^{up} _{down} @{center}");
- gr->Puts(mglPoint(0,-1),"It parse TeX: \\int \\alpha \\cdot "
- "\\sqrt3{sin(\\pi x)^2 + \\gamma_{i_k}} dx");
-
- gr->SubPlot(2,2,1,"");
- gr->Puts(mglPoint(0,0.5), "\\sqrt{\\frac{\\alpha^{\\gamma^2}+\\overset 1{\\big\\infty}}{\\sqrt3{2+b}}}", "@", -4);
- gr->Puts(mglPoint(0,-0.5),"Text can be printed\non several lines");
-
- gr->SubPlot(2,2,2,"");
- mglData y; mgls_prepare1d(&y);
- gr->Box(); gr->Plot(y.SubData(-1,0));
- gr->Text(y,"This is very very long string drawn along a curve",":k");
- gr->Text(y,"Another string drawn under a curve","T:r");
-
- gr->SubPlot(2,2,3,"");
- gr->Line(mglPoint(-1,-1),mglPoint(1,-1),"rA");
- gr->Puts(mglPoint(0,-1),mglPoint(1,-1),"Horizontal");
- gr->Line(mglPoint(-1,-1),mglPoint(1,1),"rA");
- gr->Puts(mglPoint(0,0),mglPoint(1,1),"At angle","@");
- gr->Line(mglPoint(-1,-1),mglPoint(-1,1),"rA");
- gr->Puts(mglPoint(-1,0),mglPoint(-1,1),"Vertical");
- return 0;
-}
-
-
-
-
You can change font faces by loading font files by function loadfont. Note, that this is long-run procedure. Font faces can be downloaded from MathGL website or from here. The sample code is:
-
Legend is one of standard ways to show plot annotations. Basically you need to connect the plot style (line style, marker and color) with some text. In MathGL, you can do it by 2 methods: manually using addlegend function; or use ‘legend’ option (see Command options), which will use last plot style. In both cases, legend entries will be added into internal accumulator, which later used for legend drawing itself. clearlegend function allow you to remove all saved legend entries.
-
-
There are 2 features. If plot style is empty then text will be printed without indent. If you want to plot the text with indent but without plot sample then you need to use space ‘’ as plot style. Such style ‘’ will draw a plot sample (line with marker(s)) which is invisible line (i.e. nothing) and print the text with indent as usual one.
-
-
Function legend draw legend on the plot. The position of the legend can be selected automatic or manually. You can change the size and style of text labels, as well as setup the plot sample. The sample code demonstrating legend features is:
-
The last common thing which I want to show in this section is how one can cut off points from plot. There are 4 mechanism for that.
-
-
You can set one of coordinate to NAN value. All points with NAN values will be omitted.
-
-
You can enable cutting at edges by SetCut function. As result all points out of bounding box will be omitted.
-
-
You can set cutting box by SetCutBox function. All points inside this box will be omitted.
-
-
You can define cutting formula by SetCutOff function. All points for which the value of formula is nonzero will be omitted. Note, that this is the slowest variant.
-
-
-
Below I place the code which demonstrate last 3 possibilities:
-
Class mglData contains all functions for the data handling in MathGL (see Data processing). There are several matters why I use class mglData but not a single array: it does not depend on type of data (mreal or double), sizes of data arrays are kept with data, memory working is simpler and safer.
-
FILE *fp=fopen("sin.dat","wt"); // create file first
- for(int i=0;i<50;i++) fprintf(fp,"%g\n",sin(M_PI*i/49.));
- fclose(fp);
-
- mglData y("sin.dat"); // load it
-
At this you can use textual or HDF files, as well as import values from bitmap image (PNG is supported right now).
-
-
at this one can read only part of data
-
FILE *fp-fopen("sin.dat","wt"); // create large file first
- for(int i=0;i<70;i++) fprintf(fp,"%g\n",sin(M_PI*i/49.));
- fclose(fp);
-
- mglData y;
- y.Read("sin.dat",50); // load it
-
-
-
Creation of 2d- and 3d-arrays is mostly the same. But one should keep in mind that class mglData uses flat data representation. For example, matrix 30*40 is presented as flat (1d-) array with length 30*40=1200 (nx=30, ny=40). The element with indexes {i,j} is a[i+nx*j]. So for 2d array we have:
-
The only non-obvious thing here is using multidimensional arrays in C/C++, i.e. arrays defined like mreal dat[40][30];. Since, formally these elements dat[i] can address the memory in arbitrary place you should use the proper function to convert such arrays to mglData object. For C++ this is functions like mglData::Set(mreal **dat, int N1, int N2);. For C this is functions like mgl_data_set_mreal2(HMDT d, const mreal **dat, int N1, int N2);. At this, you should keep in mind that nx=N2 and ny=N1 after conversion.
-
Sometimes the data arrays are so large, that one couldn’t’ copy its values to another array (i.e. into mglData). In this case, he can define its own class derived from mglDataA (see mglDataA class) or can use Link function.
-
-
In last case, MathGL just save the link to an external data array, but not copy it. You should provide the existence of this data array for whole time during which MathGL can use it. Another point is that MathGL will automatically create new array if you’ll try to modify data values by any of mglData functions. So, you should use only function with const modifier if you want still using link to the original data array.
-
-
Creating the link is rather simple – just the same as using Set function
-
MathGL has functions for data processing: differentiating, integrating, smoothing and so on (for more detail, see Data processing). Let us consider some examples. The simplest ones are integration and differentiation. The direction in which operation will be performed is specified by textual string, which may contain symbols ‘x’, ‘y’ or ‘z’. For example, the call of Diff("x") will differentiate data along ‘x’ direction; the call of Integral("xy") perform the double integration of data along ‘x’ and ‘y’ directions; the call of Diff2("xyz") will apply 3d Laplace operator to data and so on. Example of this operations on 2d array a=x*y is presented in code:
-
Data smoothing (function smooth) is more interesting and important. This function has single argument which define type of smoothing and its direction. Now 3 methods are supported: ‘3’ – linear averaging by 3 points, ‘5’ – linear averaging by 5 points, and default one – quadratic averaging by 5 points.
-
-
MathGL also have some amazing functions which is not so important for data processing as useful for data plotting. There are functions for finding envelope (useful for plotting rapidly oscillating data), for data sewing (useful to removing jumps on the phase), for data resizing (interpolation). Let me demonstrate it:
-
Also one can create new data arrays on base of the existing one: extract slice, row or column of data (subdata), summarize along a direction(s) (sum), find distribution of data elements (hist) and so on.
-
-
Another interesting feature of MathGL is interpolation and root-finding. There are several functions for linear and cubic spline interpolation (see Interpolation). Also there is a function evaluate which do interpolation of data array for values of each data element of index data. It look as indirect access to the data elements.
-
-
This function have inverse function solve which find array of indexes at which data array is equal to given value (i.e. work as root finding). But solve function have the issue – usually multidimensional data (2d and 3d ones) have an infinite number of indexes which give some value. This is contour lines for 2d data, or isosurface(s) for 3d data. So, solve function will return index only in given direction, assuming that other index(es) are the same as equidistant index(es) of original data. If data have multiple roots then second (and later) branches can be found by consecutive call(s) of solve function. Let me demonstrate this on the following sample.
-
Let me now show how to plot the data. Next section will give much more examples for all plotting functions. Here I just show some basics. MathGL generally has 2 types of plotting functions. Simple variant requires a single data array for plotting, other data (coordinates) are considered uniformly distributed in axis range. Second variant requires data arrays for all coordinates. It allows one to plot rather complex multivalent curves and surfaces (in case of parametric dependencies). Usually each function have one textual argument for plot style and another textual argument for options (see Command options).
-
-
Note, that the call of drawing function adds something to picture but does not clear the previous plots (as it does in Matlab). Another difference from Matlab is that all setup (like transparency, lightning, axis borders and so on) must be specified before plotting functions.
-
-
Let start for plots for 1D data. Term “1D data” means that data depend on single index (parameter) like curve in parametric form {x(i),y(i),z(i)}, i=1...n. The textual argument allow you specify styles of line and marks (see Line styles). If this parameter is NULL or empty then solid line with color from palette is used (see Palette and colors).
-
-
Below I shall show the features of 1D plotting on base of plot function. Let us start from sinus plot:
-
Style of line is not specified in plot function. So MathGL uses the solid line with first color of palette (this is blue). Next subplot shows array y1 with 2 rows:
-
As previously I did not specify the style of lines. As a result, MathGL again uses solid line with next colors in palette (there are green and red). Now let us plot a circle on the same subplot. The circle is parametric curve x=cos(\pi t), y=sin(\pi t). I will set the color of the circle (dark yellow, ‘Y’) and put marks ‘+’ at point position:
-
Note that solid line is used because I did not specify the type of line. The same picture can be achieved by plot and subdata functions. Let us draw ellipse by orange dash line:
-
Surfaces surf and other 2D plots (see 2D plotting) are drown the same simpler as 1D one. The difference is that the string parameter specifies not the line style but the color scheme of the plot (see Color scheme). Here I draw attention on 4 most interesting color schemes. There is gray scheme where color is changed from black to white (string ‘kw’) or from white to black (string ‘wk’). Another scheme is useful for accentuation of negative (by blue color) and positive (by red color) regions on plot (string ‘"BbwrR"’). Last one is the popular “jet” scheme (string ‘"BbcyrR"’).
-
-
Now I shall show the example of a surface drawing. At first let us switch lightning on
-
int sample(mglGraph *gr)
-{
- gr->Light(true); gr->Light(0,mglPoint(0,0,1));
-
and draw the surface, considering coordinates x,y to be uniformly distributed in axis range
-
Color scheme was not specified. So previous color scheme is used. In this case it is default color scheme (“jet”) for the first plot. Next example is a sphere. The sphere is parametrically specified surface:
-
Drawing of other 2D plots is analogous. The only peculiarity is the usage of flag ‘#’. By default this flag switches on the drawing of a grid on plot (grid or mesh for plots in plain or in volume). However, for isosurfaces (including surfaces of rotation axial) this flag switches the face drawing off and figure becomes wired. The following code gives example of flag ‘#’ using (compare with normal function drawing as in its description):
-
In this section I’ve included some small hints and advices for the improving of the quality of plots and for the demonstration of some non-trivial features of MathGL library. In contrast to previous examples I showed mostly the idea but not the whole drawing function.
-
As I noted above, MathGL functions (except the special one, like Clf()) do not erase the previous plotting but just add the new one. It allows one to draw “compound” plots easily. For example, popular Matlab command surfc can be emulated in MathGL by 2 calls:
-
Surf(a);
- Cont(a, "_"); // draw contours at bottom
-
Here a is 2-dimensional data for the plotting, -1 is the value of z-coordinate at which the contour should be plotted (at the bottom in this example). Analogously, one can draw density plot instead of contour lines and so on.
-
-
Another nice plot is contour lines plotted directly on the surface:
-
Light(true); // switch on light for the surface
- Surf(a, "BbcyrR"); // select 'jet' colormap for the surface
- Cont(a, "y"); // and yellow color for contours
-
The possible difficulties arise in black&white case, when the color of the surface can be close to the color of a contour line. In that case I may suggest the following code:
-
Light(true); // switch on light for the surface
- Surf(a, "kw"); // select 'gray' colormap for the surface
- CAxis(-1,0); // first draw for darker surface colors
- Cont(a, "w"); // white contours
- CAxis(0,1); // now draw for brighter surface colors
- Cont(a, "k"); // black contours
- CAxis(-1,1); // return color range to original state
-
The idea is to divide the color range on 2 parts (dark and bright) and to select the contrasting color for contour lines for each of part.
-
-
Similarly, one can plot flow thread over density plot of vector field amplitude (this is another amusing plot from Matlab) and so on. The list of compound graphics can be prolonged but I hope that the general idea is clear.
-
-
Just for illustration I put here following sample code:
-
MathGL library has advanced features for setting and handling the surface transparency. The simplest way to add transparency is the using of function alpha. As a result, all further surfaces (and isosurfaces, density plots and so on) become transparent. However, their look can be additionally improved.
-
-
The value of transparency can be different from surface to surface. To do it just use SetAlphaDef before the drawing of the surface, or use option alpha (see Command options). If its value is close to 0 then the surface becomes more and more transparent. Contrary, if its value is close to 1 then the surface becomes practically non-transparent.
-
-
Also you can change the way how the light goes through overlapped surfaces. The function SetTranspType defines it. By default the usual transparency is used (‘0’) – surfaces below is less visible than the upper ones. A “glass-like” transparency (‘1’) has a different look – each surface just decreases the background light (the surfaces are commutable in this case).
-
-
A “neon-like” transparency (‘2’) has more interesting look. In this case a surface is the light source (like a lamp on the dark background) and just adds some intensity to the color. At this, the library sets automatically the black color for the background and changes the default line color to white.
-
-
As example I shall show several plots for different types of transparency. The code is the same except the values of SetTranspType function:
-
You can easily make 3D plot and draw its x-,y-,z-projections (like in CAD) by using ternary function with arguments: 4 for Cartesian, 5 for Ternary and 6 for Quaternary coordinates. The sample code is:
-
MathGL can add a fog to the image. Its switching on is rather simple – just use fog function. There is the only feature – fog is applied for whole image. Not to particular subplot. The sample code is:
-
In contrast to the most of other programs, MathGL supports several (up to 10) light sources. Moreover, the color each of them can be different: white (this is usual), yellow, red, cyan, green and so on. The use of several light sources may be interesting for the highlighting of some peculiarities of the plot or just to make an amusing picture. Note, each light source can be switched on/off individually. The sample code is:
-
Additionally, you can use local light sources and set to use diffuse reflection instead of specular one (by default) or both kinds. Note, I use attachlight command to keep light settings relative to subplot.
-
MathGL provide a set of functions for drawing primitives (see Primitives). Primitives are low level object, which used by most of plotting functions. Picture below demonstrate some of commonly used primitives.
-
-
-
-
Generally, you can create arbitrary new kind of plot using primitives. For example, MathGL don’t provide any special functions for drawing molecules. However, you can do it using only one type of primitives drop. The sample code is:
-
Moreover, some of special plots can be more easily produced by primitives rather than by specialized function. For example, Venn diagram can be produced by Error plot:
-
Short-time Fourier Analysis (stfa) is one of informative method for analyzing long rapidly oscillating 1D data arrays. It is used to determine the sinusoidal frequency and phase content of local sections of a signal as it changes over time.
-
-
MathGL can find and draw STFA result. Just to show this feature I give following sample. Initial data arrays is 1D arrays with step-like frequency. Exactly this you can see at bottom on the STFA plot. The sample code is:
-
Sometime ago I worked with mapping and have a question about its visualization. Let me remember you that mapping is some transformation rule for one set of number to another one. The 1d mapping is just an ordinary function – it takes a number and transforms it to another one. The 2d mapping (which I used) is a pair of functions which take 2 numbers and transform them to another 2 ones. Except general plots (like surfc, surfa) there is a special plot – Arnold diagram. It shows the area which is the result of mapping of some initial area (usually square).
-
-
I tried to make such plot in map. It shows the set of points or set of faces, which final position is the result of mapping. At this, the color gives information about their initial position and the height describes Jacobian value of the transformation. Unfortunately, it looks good only for the simplest mapping but for the real multivalent quasi-chaotic mapping it produces a confusion. So, use it if you like :).
-
functions subdata and evaluate for indirect access to data elements;
-
functions refill, gspline and datagrid which fill regular (rectangular) data array by interpolated values.
-
-
-
The usage of first category is rather straightforward and don’t need any special comments.
-
-
There is difference in indirect access functions. Function subdata use use step-like interpolation to handle correctly single nan values in the data array. Contrary, function evaluate use local spline interpolation, which give smoother output but spread nan values. So, subdata should be used for specific data elements (for example, for given column), and evaluate should be used for distributed elements (i.e. consider data array as some field). Following sample illustrates this difference:
-
int sample(mglGraph *gr)
-{
- gr->SubPlot(1,1,0,""); gr->Title("SubData vs Evaluate");
- mglData in(9), arg(99), e, s;
- gr->Fill(in,"x^3/1.1"); gr->Fill(arg,"4*x+4");
- gr->Plot(in,"ko "); gr->Box();
- e = in.Evaluate(arg,false); gr->Plot(e,"b.","legend 'Evaluate'");
- s = in.SubData(arg); gr->Plot(s,"r.","legend 'SubData'");
- gr->Legend(2);
-}
-
-
-
-
Example of datagrid usage is done in Making regular data. Here I want to show the peculiarities of refill and gspline functions. Both functions require argument(s) which provide coordinates of the data values, and return rectangular data array which equidistantly distributed in axis range. So, in opposite to evaluate function, refill and gspline can interpolate non-equidistantly distributed data. At this both functions refill and gspline provide continuity of 2nd derivatives along coordinate(s). However, refill is slower but give better (from human point of view) result than global spline gspline due to more advanced algorithm. Following sample illustrates this difference:
-
Sometimes, one have only unregular data, like as data on triangular grids, or experimental results and so on. Such kind of data cannot be used as simple as regular data (like matrices). Only few functions, like dots, can handle unregular data as is.
-
-
However, one can use built in triangulation functions for interpolating unregular data points to a regular data grids. There are 2 ways. First way, one can use triangulation function to obtain list of vertexes for triangles. Later this list can be used in functions like triplot or tricont. Second way consist in usage of datagrid function, which fill regular data grid by interpolated values, assuming that coordinates of the data grid is equidistantly distributed in axis range. Note, you can use options (see Command options) to change default axis range as well as in other plotting functions.
-
int sample(mglGraph *gr)
-{
- mglData x(100), y(100), z(100);
- gr->Fill(x,"2*rnd-1"); gr->Fill(y,"2*rnd-1"); gr->Fill(z,"v^2-w^2",x,y);
- // first way - plot triangular surface for points
- mglData d = mglTriangulation(x,y);
- gr->Title("Triangulation");
- gr->Rotate(40,60); gr->Box(); gr->Light(true);
- gr->TriPlot(d,x,y,z); gr->TriPlot(d,x,y,z,"#k");
- // second way - make regular data and plot it
- mglData g(30,30);
- gr->DataGrid(g,x,y,z); gr->Mesh(g,"m");
-}
-
Using the hist function(s) for making regular distributions is one of useful fast methods to process and plot irregular data. Hist can be used to find some momentum of set of points by specifying weight function. It is possible to create not only 1D distributions but also 2D and 3D ones. Below I place the simplest sample code which demonstrate hist usage:
-
Nonlinear fitting is rather simple. All that you need is the data to fit, the approximation formula and the list of coefficients to fit (better with its initial guess values). Let me demonstrate it on the following simple example. First, let us use sin function with some random noise:
-
mglData dat(100), in(100); //data to be fitted and ideal data
- gr->Fill(dat,"0.4*rnd+0.1+sin(2*pi*x)");
- gr->Fill(in,"0.3+sin(2*pi*x)");
-
The next step is the fitting itself. For that let me specify an initial values ini for coefficients ‘abc’ and do the fitting for approximation formula ‘a+b*sin(c*x)’
-
NOTE! the fitting results may have strong dependence on initial values for coefficients due to algorithm features. The problem is that in general case there are several local "optimums" for coefficients and the program returns only first found one! There are no guaranties that it will be the best. Try for example to set ini[3] = {0, 0, 0} in the code above.
-
Solving of Partial Differential Equations (PDE, including beam tracing) and ray tracing (or finding particle trajectory) are more or less common task. So, MathGL have several functions for that. There are ray for ray tracing, pde for PDE solving, qo2d for beam tracing in 2D case (see Global functions). Note, that these functions take “Hamiltonian” or equations as string values. And I don’t plan now to allow one to use user-defined functions. There are 2 reasons: the complexity of corresponding interface; and the basic nature of used methods which are good for samples but may not good for serious scientific calculations.
-
-
The ray tracing can be done by ray function. Really ray tracing equation is Hamiltonian equation for 3D space. So, the function can be also used for finding a particle trajectory (i.e. solve Hamiltonian ODE) for 1D, 2D or 3D cases. The function have a set of arguments. First of all, it is Hamiltonian which defined the media (or the equation) you are planning to use. The Hamiltonian is defined by string which may depend on coordinates ‘x’, ‘y’, ‘z’, time ‘t’ (for particle dynamics) and momentums ‘p’=p_x, ‘q’=p_y, ‘v’=p_z. Next, you have to define the initial conditions for coordinates and momentums at ‘t’=0 and set the integrations step (default is 0.1) and its duration (default is 10). The Runge-Kutta method of 4-th order is used for integration.
-
This example calculate the reflection from linear layer (media with Hamiltonian ‘p^2+q^2-x-1’=p_x^2+p_y^2-x-1). This is parabolic curve. The resulting array have 7 columns which contain data for {x,y,z,p,q,v,t}.
-
-
The solution of PDE is a bit more complicated. As previous you have to specify the equation as pseudo-differential operator \hat H(x, \nabla) which is called sometime as “Hamiltonian” (for example, in beam tracing). As previously, it is defined by string which may depend on coordinates ‘x’, ‘y’, ‘z’ (but not time!), momentums ‘p’=(d/dx)/i k_0, ‘q’=(d/dy)/i k_0 and field amplitude ‘u’=|u|. The evolutionary coordinate is ‘z’ in all cases. So that, the equation look like du/dz = ik_0 H(x,y,\hat p, \hat q, |u|)[u]. Dependence on field amplitude ‘u’=|u| allows one to solve nonlinear problems too. For example, for nonlinear Shrodinger equation you may set ham="p^2 + q^2 - u^2". Also you may specify imaginary part for wave absorption, like ham = "p^2 + i*x*(x>0)" or ham = "p^2 + i1*x*(x>0)".
-
-
Next step is specifying the initial conditions at ‘z’ equal to minimal z-axis value. The function need 2 arrays for real and for imaginary part. Note, that coordinates x,y,z are supposed to be in specified axis range. So, the data arrays should have corresponding scales. Finally, you may set the integration step and parameter k0=k_0. Also keep in mind, that internally the 2 times large box is used (for suppressing numerical reflection from boundaries) and the equation should well defined even in this extended range.
-
-
Final comment is concerning the possible form of pseudo-differential operator H. At this moment, simplified form of operator H is supported – all “mixed” terms (like ‘x*p’->x*d/dx) are excluded. For example, in 2D case this operator is effectively H = f(p,z) + g(x,z,u). However commutable combinations (like ‘x*q’->x*d/dy) are allowed for 3D case.
-
-
So, for example let solve the equation for beam deflected from linear layer and absorbed later. The operator will have the form ‘"p^2+q^2-x-1+i*0.5*(z+x)*(z>-x)"’ that correspond to equation 1/ik_0 * du/dz + d^2 u/dx^2 + d^2 u/dy^2 + x * u + i (x+z)/2 * u = 0. This is typical equation for Electron Cyclotron (EC) absorption in magnetized plasmas. For initial conditions let me select the beam with plane phase front exp(-48*(x+0.7)^2). The corresponding code looks like this:
-
int sample(mglGraph *gr)
-{
- mglData a,re(128),im(128);
- gr->Fill(re,"exp(-48*(x+0.7)^2)");
- a = gr->PDE("p^2+q^2-x-1+i*0.5*(z+x)*(z>-x)", re, im, 0.01, 30);
- a.Transpose("yxz");
- gr->SubPlot(1,1,0,"<_"); gr->Title("PDE solver");
- gr->SetRange('c',0,1); gr->Dens(a,"wyrRk");
- gr->Axis(); gr->Label('x', "\\i x"); gr->Label('y', "\\i z");
- gr->FPlot("-x", "k|");
- gr->Puts(mglPoint(0, 0.85), "absorption: (x+z)/2 for x+z>0");
- gr->Puts(mglPoint(0,1.1),"Equation: ik_0\\partial_zu + \\Delta u + x\\cdot u + i \\frac{x+z}{2}\\cdot u = 0");
- return 0;
-}
-
-
-
-
The next example is the beam tracing. Beam tracing equation is special kind of PDE equation written in coordinates accompanied to a ray. Generally this is the same parameters and limitation as for PDE solving but the coordinates are defined by the ray and by parameter of grid width w in direction transverse the ray. So, you don’t need to specify the range of coordinates. BUT there is limitation. The accompanied coordinates are well defined only for smooth enough rays, i.e. then the ray curvature K (which is defined as 1/K^2 = (|r''|^2 |r'|^2 - (r'', r'')^2)/|r'|^6) is much large then the grid width: K>>w. So, you may receive incorrect results if this condition will be broken.
-
-
You may use following code for obtaining the same solution as in previous example:
-
int sample(mglGraph *gr)
-{
- mglData r, xx, yy, a, im(128), re(128);
- const char *ham = "p^2+q^2-x-1+i*0.5*(y+x)*(y>-x)";
- r = mglRay(ham, mglPoint(-0.7, -1), mglPoint(0, 0.5), 0.02, 2);
- gr->SubPlot(1,1,0,"<_"); gr->Title("Beam and ray tracing");
- gr->Plot(r.SubData(0), r.SubData(1), "k");
- gr->Axis(); gr->Label('x', "\\i x"); gr->Label('y', "\\i z");
-
- // now start beam tracing
- gr->Fill(re,"exp(-48*x^2)");
- a = mglQO2d(ham, re, im, r, xx, yy, 1, 30);
- gr->SetRange('c',0, 1);
- gr->Dens(xx, yy, a, "wyrRk");
- gr->FPlot("-x", "k|");
- gr->Puts(mglPoint(0, 0.85), "absorption: (x+y)/2 for x+y>0");
- gr->Puts(mglPoint(0.7, -0.05), "central ray");
- return 0;
-}
-
-
-
-
Note, the pde is fast enough and suitable for many cases routine. However, there is situations then media have both together: strong spatial dispersion and spatial inhomogeneity. In this, case the pde will produce incorrect result and you need to use advanced PDE solver apde. For example, a wave beam, propagated in plasma, described by Hamiltonian exp(-x^2-p^2), will have different solution for using of simplification and advanced PDE solver:
-
Here I want say a few words of plotting phase plains. Phase plain is name for system of coordinates x, x', i.e. a variable and its time derivative. Plot in phase plain is very useful for qualitative analysis of an ODE, because such plot is rude (it topologically the same for a range of ODE parameters). Most often the phase plain {x, x'} is used (due to its simplicity), that allows to analyze up to the 2nd order ODE (i.e. x''+f(x,x')=0).
-
-
The simplest way to draw phase plain in MathGL is using flow function(s), which automatically select several points and draw flow threads. If the ODE have an integral of motion (like Hamiltonian H(x,x')=const for dissipation-free case) then you can use cont function for plotting isolines (contours). In fact. isolines are the same as flow threads, but without arrows on it. Finally, you can directly solve ODE using ode function and plot its numerical solution.
-
-
Let demonstrate this for ODE equation x''-x+3*x^2=0. This is nonlinear oscillator with square nonlinearity. It has integral H=y^2+2*x^3-x^2=Const. Also it have 2 typical stationary points: saddle at {x=0, y=0} and center at {x=1/3, y=0}. Motion at vicinity of center is just simple oscillations, and is stable to small variation of parameters. In opposite, motion around saddle point is non-stable to small variation of parameters, and is very slow. So, calculation around saddle points are more difficult, but more important. Saddle points are responsible for solitons, stochasticity and so on.
-
-
So, let draw this phase plain by 3 different methods. First, draw isolines for H=y^2+2*x^3-x^2=Const – this is simplest for ODE without dissipation. Next, draw flow threads – this is straightforward way, but the automatic choice of starting points is not always optimal. Finally, use ode to check the above plots. At this we need to run ode in both direction of time (in future and in the past) to draw whole plain. Alternatively, one can put starting points far from (or at the bounding box as done in flow) the plot, but this is a more complicated. The sample code is:
-
There is common task in optics to determine properties of wave pulses or wave beams. MathGL provide special function pulse which return the pulse properties (maximal value, center of mass, width and so on). Its usage is rather simple. Here I just illustrate it on the example of Gaussian pulse, where all parameters are obvious.
-
void sample(mglGraph *gr)
-{
- gr->SubPlot(1,1,0,"<_"); gr->Title("Pulse sample");
- // first prepare pulse itself
- mglData a(100); gr->Fill(a,"exp(-6*x^2)");
- // get pulse parameters
- mglData b(a.Pulse('x'));
- // positions and widths are normalized on the number of points. So, set proper axis scale.
- gr->SetRanges(0, a.nx-1, 0, 1);
- gr->Axis(); gr->Plot(a); // draw pulse and axis
- // now visualize found pulse properties
- double m = b[0]; // maximal amplitude
- // approximate position of maximum
- gr->Line(mglPoint(b[1],0), mglPoint(b[1],m),"r=");
- // width at half-maximum (so called FWHM)
- gr->Line(mglPoint(b[1]-b[3]/2,0), mglPoint(b[1]-b[3]/2,m),"m|");
- gr->Line(mglPoint(b[1]+b[3]/2,0), mglPoint(b[1]+b[3]/2,m),"m|");
- gr->Line(mglPoint(0,m/2), mglPoint(a.nx-1,m/2),"h");
- // parabolic approximation near maximum
- char func[128]; sprintf(func,"%g*(1-((x-%g)/%g)^2)",b[0],b[1],b[2]);
- gr->FPlot(func,"g");
-}
-
Sometimes you may prefer to use MGL scripts in yours code. It is simpler (especially in comparison with C/Fortran interfaces) and provide faster way to plot the data with annotations, labels and so on. Class mglParse (see mglParse class parse MGL scripts in C++. It have also the corresponding interface for C/Fortran.
-
-
The key function here is mglParse::Parse() (or mgl_parse() for C/Fortran) which execute one command per string. At this the detailed information about the possible errors or warnings is passed as function value. Or you may execute the whole script as long string with lines separated by ‘\n’. Functions mglParse::Execute() and mgl_parse_text() perform it. Also you may set the values of parameters ‘$0’...‘$9’ for the script by functions mglParse::AddParam() or mgl_add_param(), allow/disable picture resizing, check “once” status and so on. The usage is rather straight-forward.
-
-
The only non-obvious thing is data transition between script and yours program. There are 2 stages: add or find variable; and set data to variable. In C++ you may use functions mglParse::AddVar() and mglParse::FindVar() which return pointer to mglData. In C/Fortran the corresponding functions are mgl_add_var(), mgl_find_var(). This data pointer is valid until next Parse() or Execute() call. Note, you must not delete or free the data obtained from these functions!
-
-
So, some simple example at the end. Here I define a data array, create variable, put data into it and plot it. The C++ code looks like this:
-
int sample(mglGraph *gr)
-{
- gr->Title("MGL parser sample");
- mreal a[100]; // let a_i = sin(4*pi*x), x=0...1
- for(int i=0;i<100;i++)a[i]=sin(4*M_PI*i/99);
- mglParse *parser = new mglParse;
- mglData *d = parser->AddVar("dat");
- d->Set(a,100); // set data to variable
- parser->Execute(gr, "plot dat; xrange 0 1\nbox\naxis");
- // you may break script at any line do something
- // and continue after that
- parser->Execute(gr, "xlabel 'x'\nylabel 'y'\nbox");
- // also you may use cycles or conditions in script
- parser->Execute(gr, "for $0 -1 1 0.1\nif $0<0\n"
- "line 0 0 -1 $0 'r':else:line 0 0 -1 $0 'g'\n"
- "endif\nnext");
- delete parser;
- return 0;
-}
-
The code in C/Fortran looks practically the same:
-
int sample(HMGL gr)
-{
- mgl_title(gr, "MGL parser sample", "", -2);
- double a[100]; // let a_i = sin(4*pi*x), x=0...1
- int i;
- for(i=0;i<100;i++) a[i]=sin(4*M_PI*i/99);
- HMPR parser = mgl_create_parser();
- HMDT d = mgl_parser_add_var(parser, "dat");
- mgl_data_set_double(d,a,100,1,1); // set data to variable
- mgl_parse_text(gr, parser, "plot dat; xrange 0 1\nbox\naxis");
- // you may break script at any line do something
- // and continue after that
- mgl_parse_text(gr, parser, "xlabel 'x'\nylabel 'y'");
- // also you may use cycles or conditions in script
- mgl_parse_text(gr, parser, "for $0 -1 1 0.1\nif $0<0\n"
- "line 0 0 -1 $0 'r':else:line 0 0 -1 $0 'g'\n"
- "endif\nnext");
- mgl_write_png(gr, "test.png", ""); // don't forgot to save picture
- return 0;
-}
-
Command options allow the easy setup of the selected plot by changing global settings only for this plot. Often, options are used for specifying the range of automatic variables (coordinates). However, options allows easily change plot transparency, numbers of line or faces to be drawn, or add legend entries. The sample function for options usage is:
-
As I have noted before, the change of settings will influence only for the further plotting commands. This allows one to create “template” function which will contain settings and primitive drawing for often used plots. Correspondingly one may call this template-function for drawing simplification.
-
-
For example, let one has a set of points (experimental or numerical) and wants to compare it with theoretical law (for example, with exponent law \exp(-x/2), x \in [0, 20]). The template-function for this task is:
-
At this, one will only write a few lines for data drawing:
-
template(gr); // apply settings and default drawing from template
- mglData dat("fname.dat"); // load the data
- // and draw it (suppose that data file have 2 columns)
- gr->Plot(dat.SubData(0),dat.SubData(1),"bx ");
-
A template-function can also contain settings for font, transparency, lightning, color scheme and so on.
-
-
I understand that this is obvious thing for any professional programmer, but I several times receive suggestion about “templates” ... So, I decide to point out it here.
-
One can easily create stereo image in MathGL. Stereo image can be produced by making two subplots with slightly different rotation angles. The corresponding code looks like this:
-
By default MathGL save all primitives in memory, rearrange it and only later draw them on bitmaps. Usually, this speed up drawing, but may require a lot of memory for plots which contain a lot of faces (like cloud, dew). You can use quality function for setting to use direct drawing on bitmap and bypassing keeping any primitives in memory. This function also allow you to decrease the quality of the resulting image but increase the speed of the drawing.
-
-
The code for lowest memory usage looks like this:
-
int sample(mglGraph *gr)
-{
- gr->SetQuality(6); // firstly, set to draw directly on bitmap
- for(i=0;i<1000;i++)
- gr->Sphere(mglPoint(mgl_rnd()*2-1,mgl_rnd()*2-1),0.05);
- return 0;
-}
-
MathGL have possibilities to write textual information into file with variable values. In MGL script you can use save command for that. However, the usual printf(); is simple in C/C++ code. For example, lets create some textual file
-
FILE *fp=fopen("test.txt","w");
-fprintf(fp,"This is test: 0 -> 1 q\n");
-fprintf(fp,"This is test: 1 -> -1 q\n");
-fprintf(fp,"This is test: 2 -> 0 q\n");
-fclose(fp);
-
It contents look like
-
This is test: 0 -> 1 q
-This is test: 1 -> -1 q
-This is test: 2 -> 0 q
-
-
Let assume now that you want to read this values (i.e. [[0,1],[1,-1],[2,0]]) from the file. You can use scanfile for that. The desired values was written using template "This is test: %g -> %g q\n". So, just use
-
mglData a;
-a.ScanFile("test.txt","This is test: %g -> %g");
-
Note, I keep only the leading part of template (i.e. "This is test: %g -> %g" instead of "This is test: %g -> %g q\n"), because there is no important for us information after the second number in the line.
-
Sometimes output plots contain surfaces with a lot of points, and some vector primitives (like axis, text, curves, etc.). Using vector output formats (like EPS or SVG) will produce huge files with possible loss of smoothed lighting. Contrary, the bitmap output may cause the roughness of text and curves. Hopefully, MathGL have a possibility to combine bitmap output for surfaces and vector one for other primitives in the same EPS file, by using rasterize command.
-
-
The idea is to prepare part of picture with surfaces or other "heavy" plots and produce the background image from them by help of rasterize command. Next, we draw everything to be saved in vector form (text, curves, axis and etc.). Note, that you need to clear primitives (use clf command) after rasterize if you want to disable duplication of surfaces in output files (like EPS). Note, that some of output formats (like 3D ones, and TeX) don’t support the background bitmap, and use clf for them will cause the loss of part of picture.
-
-
The sample code is:
-
// first draw everything to be in bitmap output
-gr->FSurf("x^2+y^2", "#", "value 10");
-
-gr->Rasterize(); // set above plots as bitmap background
-gr->Clf(); // clear primitives, to exclude them from file
-
-// now draw everything to be in vector output
-gr->Axis(); gr->Box();
-
-// and save file
-gr->WriteFrame("fname.eps");
-
Check that points of the plot are located inside the bounding box and resize the bounding box using ranges function. Check that the data have correct dimensions for selected type of plot. Be sure that Finish() is called after the plotting functions (or be sure that the plot is saved to a file). Sometimes the light reflection from flat surfaces (like, dens) can look as if the plot were absent.
-
-
-
I can not find some special kind of plot.
-
Most “new” types of plots can be created by using the existing drawing functions. For example, the surface of curve rotation can be created by a special function torus, or as a parametrically specified surface by surf. See also, Hints. If you can not find a specific type of plot, please e-mail me and this plot will appear in the next version of MathGL library.
-
-
-
Should I know some graphical libraries (like OpenGL) before using the MathGL library?
-
No. The MathGL library is self-contained and does not require the knowledge of external libraries.
-
-
-
In which language is the library written? For which languages does it have an interface?
-
The core of the MathGL library is written in C++. But there are interfaces for: pure C, Fortran, Pascal, Forth, and its own command language MGL. Also there is a large set of interpreted languages, which are supported (Python, Java, ALLEGROCL, CHICKEN, Lisp, CFFI, C#, Guile, Lua, Modula 3, Mzscheme, Ocaml, Octave, Perl, PHP, Pike, R, Ruby, Tcl). These interfaces are written using SWIG (both pure C functions and classes) but only the interface for Python and Octave is included in the build system. The reason is that I don’t know any other interpreted languages :(. Note that most other languages can use (link to) the pure C functions.
-
-
-
How can I use MathGL with Fortran?
-
You can use MathGL as is with gfortran because it uses by default the AT&T notation for external functions. For other compilers (like Visual Fortran) you have to switch on the AT&T notation manually. The AT&T notation requires that the symbol ‘_’ is added at the end of each function name, function argument(s) is passed by pointers and the string length(s) is passed at the end of the argument list. For example:
-
-
C function – void mgl_fplot(HMGL graph, const char *fy, const char *stl, int n);
-
-
AT&T function – void mgl_fplot_(uintptr_t *graph, const char *fy, const char *stl, int *n, int ly, int ls);
-
-
Fortran users also should add C++ library by the option -lstdc++. If library was built with enable-double=ON (this default for v.2.1 and later) then all real numbers must be real*8. You can make it automatic if use option -fdefault-real-8.
-
-
-
How can I print in Russian/Spanish/Arabic/Japanese, and so on?
-
The standard way is to use Unicode encoding for the text output. But the MathGL library also has interface for 8-bit (char *) strings with internal conversion to Unicode. This conversion depends on the current locale OS. You may change it by setlocale() function. For example, for Russian text in CP1251 encoding you may use setlocale(LC_CTYPE, "ru_RU.cp1251"); (under MS Windows the name of locale may differ – setlocale(LC_CTYPE, "russian_russia.1251")). I strongly recommend not to use the constant LC_ALL in the conversion. Since it also changes the number format, it may lead to mistakes in formula writing and reading of the text in data files. For example, the program will await a ‘,’ as a decimal point but the user will enter ‘.’.
-
-
-
How can I exclude a point or a region of plot from the drawing?
-
There are 3 general ways. First, the point with NAN value as one of the coordinates (including color/alpha range) will never be plotted. Second, special functions SetCutBox() and CutOff() define the condition when the points should be omitted (see Cutting). Last, you may change the transparency of a part of the plot by the help of functions surfa, surf3a (see Dual plotting). In last case the transparency is switched on smoothly.
-
-
-
I use VisualStudio, CBuilder or some other compiler (not MinGW/gcc). How can I link the MathGL library?
-
In version 2.0, main classes (mglGraph and mglData) contains only inline functions and are acceptable for any compiler with the same binary files. However, if you plan to use widget classes (QMathGL, Fl_MathGL, ...) or to access low-level features (mglBase, mglCanvas, ...) then you have to recompile MathGL by yours compiler.
-
-
Note, that you have to make import library(-ies) *.lib for provided binary *.dll. This procedure depend on used compiler – please read documentation for yours compiler. For VisualStudio, it can be done by command lib.exe /DEF:libmgl.def /OUT:libmgl.lib.
-
-
-
How make FLTK/GLUT/Qt window which will display result of my calculations?
-
-
You need to put yours calculations or main event-handling loop in the separate thread. For static image you can give NULL as drawing function and call Update() function when you need to redraw it. For more details see Animation.
-
-
-
How I can build MathGL under Windows?
-
Generally, it is the same procedure as for Linux or MacOS – see section Installation. The simplest way is using the combination CMake+MinGW. Also you may need some extra libraries like GSL, PNG, JPEG and so on. All of them can be found at http://gnuwin32.sourceforge.net/packages.html. After installing all components, just run cmake-gui configurator and build the MathGL itself.
-
-
-
How many people write this library?
-
Most of the library was written by one person. This is a result of nearly a year of work (mostly in the evening and on holidays): I spent half a year to write the kernel and half a year to a year on extending, improving the library and writing documentation. This process continues now :). The build system (cmake files) was written mostly by D.Kulagin, and the export to PRC/PDF was written mostly by M.Vidassov.
-
-
-
How can I display a bitmap on the figure?
-
You can import data into a mglData instance by function import and display it by dens function. For example, for black-and-white bitmap you can use the code: mglData bmp; bmp.Import("fname.png","wk"); gr->Dens(bmp,"wk");.
-
-
-
How can I use MathGL in Qt, FLTK, wxWidgets etc.?
-
There are special classes (widgets) for these libraries: QMathGL for Qt, Fl_MathGL for FLTK and so on. If you don’t find the appropriate class then you can create your own widget that displays a bitmap using mglCanvas::GetRGB().
-
-
-
How can I create 3D in PDF?
-
Just use WritePRC() method which also create PDF file if enable-pdf=ON at MathGL configure.
-
-
-
How can I create TeX figure?
-
Just use WriteTEX() method which create LaTeX files with figure itself ‘fname.tex’, with MathGL colors ‘mglcolors.tex’ and main file ‘mglmain.tex’. Last one can be used for viewing image by command like pdflatex mglmain.tex.
-
-
-
Can I use MathGL in JavaScript?
-
Yes, sample JavaScript file is located in texinfo/ folder of sources. You should provide JSON data with 3d image for it (can be created by WriteJSON() method). Script allows basic manipulation with plot: zoom, rotation, shift. Sample of JavaScript pictures can be found in http://mathgl.sf.net/json.html.
-
-
-
-
-
-
How I can change the font family?
-
First, you should download new font files from here or from here. Next, you should load the font files into mglGraph class instance gr by the following command: gr->LoadFont(fontname,path);. Here fontname is the base font name like ‘STIX’ and path sets the location of font files. Use gr->RestoreFont(); to start using the default font.
-
-
-
How can I draw tick out of a bounding box?
-
Just set a negative value in ticklen. For example, use gr->SetTickLen(-0.1);.
-
-
-
How can I prevent text rotation?
-
Just use SetRotatedText(false). Also you can use axis style ‘U’ for disable only tick labels rotation.
-
How can I draw equal axis range even for rectangular image?
-
Just use Aspect(NAN,NAN) for each subplot, or at the beginning of the drawing.
-
-
-
How I can set transparent background?
-
Just use code like Clf("r{A5}"); or prepare PNG file and set it as background image by call LoadBackground("fname.png");.
-
-
-
How I can reduce "white" edges around bounding box?
-
The simplest way is to use subplot style. However, you should be careful if you plan to add colorbar or rotate plot – part of plot can be invisible if you will use non-default subplot style.
-
-
-
Can I combine bitmap and vector output in EPS?
-
Yes. Sometimes you may have huge surface and a small set of curves and/or text on the plot. You can use function rasterize just after making surface plot. This will put all plot to bitmap background. At this later plotting will be in vector format. For example, you can do something like following:
-
gr->Surf(x, y, z);
-gr->Rasterize(); // make surface as bitmap
-gr->Axis();
-gr->WriteFrame("fname.eps");
-
-
-
Why I couldn’t use name ‘I’ for variable?
-
MathGL support C99 standard, where ‘I’ is reserved for imaginary unit. If you still need this name, then just use
-
#undef I
-
after including MathGL header files.
-
-
-
How I can create MPEG video from plots?
-
You can save each frame into JPEG with names like ‘frame0001.jpg’, ‘frame0002.jpg’, ... Later you can use ImageMagic to convert them into MPEG video by command convert frame*.jpg movie.mpg. See also MPEG.
-
The set of MathGL features is rather rich – just the number of basic graphics types
-is larger than 50. Also there are functions for data handling, plot setup and so on. In spite of it I tried to keep a similar style in function names and in the order of arguments. Mostly it is
-used for different drawing functions.
-
-
There are six most general (base) concepts:
-
-
Any picture is created in memory first. The internal (memory) representation can be different: bitmap picture (for SetQuality(MGL_DRAW_LMEM) or quality 6) or the list of vector primitives (default). After that the user may decide what he/she want: save to file, display on the screen, run animation, do additional editing and so on. This approach assures a high portability of the program – the source code will produce exactly the same picture in any OS. Another big positive consequence is the ability to create the picture in the console program (using command line, without creating a window)!
-
Every plot settings (style of lines, font, color scheme) are specified by a string. It provides convenience for user/programmer – short string with parameters is more comprehensible than a large set of parameters. Also it provides portability – the strings are the same in any OS so that it is not necessary to think about argument types.
-
All functions have “simplified” and “advanced” forms. It is done for user’s convenience. One needs to specify only one data array in the “simplified” form in order to see the result. But one may set parametric dependence of coordinates and produce rather complex curves and surfaces in the “advanced” form. In both cases the order of function arguments is the same: first data arrays, second the string with style, and later string with options for additional plot tuning.
-
All data arrays for plotting are encapsulated in mglData(A) class. This reduces the number of errors while working with memory and provides a uniform interface for data of different types (mreal, double and so on) or for formula plotting.
-
All plots are vector plots. The MathGL library is intended for handling scientific data which have vector nature (lines, faces, matrices and so on). As a result, vector representation is used in all cases! In addition, the vector representation allows one to scale the plot easily – change the canvas size by a factor of 2, and the picture will be proportionally scaled.
-
New drawing never clears things drawn already. This, in some sense, unexpected, idea allows to create a lot of “combined” graphics. For example, to make a surface with contour lines one needs to call the function for surface plotting and the function for contour lines plotting (in any order). Thus the special functions for making this “combined” plots (as it is done in Matlab and some other plotting systems) are superfluous.
-
-
-
In addition to the general concepts I want to comment on some non-trivial or less commonly used general ideas – plot positioning, axis specification and curvilinear coordinates, styles for lines, text and color scheme.
-
Two axis representations are used in MathGL. The first one consists of normalizing coordinates of data points in axis range (see Axis settings). If SetCut() is true then the outlier points are omitted, otherwise they are projected to the bounding box (see Cutting). Also, the point will be omitted if it lies inside the box defined by SetCutBox() or if the value of formula CutOff() is nonzero for its coordinates. After that, transformation formulas defined by SetFunc() or SetCoor() are applied to the data point (see Curved coordinates). Finally, the data point is plotted by one of the functions.
-
-
The range of x, y, z-axis can be specified by SetRange() or ranges functions. Its origin is specified by origin function. At this you can you can use NAN values for selecting axis origin automatically.
-
-
There is 4-th axis c (color axis or colorbar) in addition to the usual axes x, y, z. It sets the range of values for the surface coloring. Its borders are automatically set to values of z-range during the call of ranges function. Also, one can directly set it by call SetRange('c', ...). Use colorbar function for drawing the colorbar.
-
-
The form (appearence) of tick labels is controlled by SetTicks() function (see Ticks). Function SetTuneTicks switches on/off tick enhancing by factoring out acommon multiplier (for small coordinate values, like 0.001 to 0.002, or large, like from 1000 to 2000) or common component (for narrow range, like from 0.999 to 1.000). Finally, you may use functions SetTickTempl() for setting templates for tick labels (it supports TeX symbols). Also, there is a possibility to print arbitrary text as tick labels the by help of SetTicksVal() function.
-
Base colors are defined by one of symbol ‘wkrgbcymhRGBCYMHWlenupqLENUPQ’.
-
The color types are: ‘k’ – black, ‘r’ – red, ‘R’ – dark red, ‘g’ – green, ‘G’ – dark green, ‘b’ – blue, ‘B’ – dark blue, ‘c’ – cyan, ‘C’ – dark cyan, ‘m’ – magenta, ‘M’ – dark magenta, ‘y’ – yellow, ‘Y’ – dark yellow (gold), ‘h’ – gray, ‘H’ – dark gray, ‘w’ – white, ‘W’ – bright gray, ‘l’ – green-blue, ‘L’ – dark green-blue, ‘e’ – green-yellow, ‘E’ – dark green-yellow, ‘n’ – sky-blue, ‘N’ – dark sky-blue, ‘u’ – blue-violet, ‘U’ – dark blue-violet, ‘p’ – purple, ‘P’ – dark purple, ‘q’ – orange, ‘Q’ – dark orange (brown).
-
-
You can also use “bright” colors. The “bright” color contain 2 symbols in brackets ‘{cN}’: first one is the usual symbol for color id, the second one is a digit for its brightness. The digit can be in range ‘1’...‘9’. Number ‘5’ corresponds to a normal color, ‘1’ is a very dark version of the color (practically black), and ‘9’ is a very bright version of the color (practically white). For example, the colors can be ‘{b2}’ ‘{b7}’ ‘{r7}’ and so on.
-
-
Finally, you can specify RGB or RGBA values of a color using format ‘{xRRGGBB}’ or ‘{xRRGGBBAA}’ correspondingly. For example, ‘{xFF9966}’ give you
-melone color.
-
The line style is defined by the string which may contain specifications for color (‘wkrgbcymhRGBCYMHWlenupqLENUPQ’), dashing style (‘-|;:ji=’ or space), width (‘123456789’) and marks (‘*o+xsd.^v<>’ and ‘#’ modifier). If one of the type of information is omitted then default values used with next color from palette (see Palette and colors). Note, that internal color counter will be nullified by any change of palette. This includes even hidden change (for example, by box or axis functions).
-By default palette contain following colors: dark gray ‘H’, blue ‘b’, green ‘g’, red ‘r’, cyan ‘c’, magenta ‘m’, yellow ‘y’, gray ‘h’, green-blue ‘l’, sky-blue ‘n’, orange ‘q’, green-yellow ‘e’, blue-violet ‘u’, purple ‘p’.
-
-
Dashing style has the following meaning: space – no line (usable for plotting only marks), ‘-’ – solid line (■■■■■■■■■■■■■■■■), ‘|’ – long dashed line (■■■■■■■■□□□□□□□□), ‘;’ – dashed line (■■■■□□□□■■■■□□□□), ‘=’ – small dashed line (■■□□■■□□■■□□■■□□), ‘:’ – dotted line (■□□□■□□□■□□□■□□□), ‘j’ – dash-dotted line (■■■■■■■□□□□■□□□□), ‘i’ – small dash-dotted line (■■■□□■□□■■■□□■□□), ‘{dNNNN}’ – manual mask style (for v.2.3 and later, like ‘{df090}’ for (■■■■□□□□■□□■□□□□)).
You can provide user-defined symbols (see addsymbol) to draw it as marker by using ‘&’ style. In particular, ‘&*’, ‘&o’, ‘&+’, ‘&x’, ‘&s’, ‘&d’, ‘&.’, ‘&^’, ‘&v’, ‘&<’, ‘&>’ will draw user-defined symbol ‘*o+xsd.^v<>’ correspondingly; and
-‘&#o’, ‘&#+’, ‘&#x’, ‘&#s’, ‘&#d’, ‘&#.’, ‘&#^’, ‘&#v’, ‘&#<’, ‘&#>’ will draw user-defined symbols ‘YOPXSDCTVLR’ correspondingly. Note, that wired version of user-defined symbols will be drawn if you set negative marker size (see marksize or size in Command options).
-
-
One may specify to draw a special symbol (an arrow) at the beginning and at the end of line. This is done if the specification string contains one of the following symbols: ‘A’ – outer arrow, ‘V’ – inner arrow, ‘I’ – transverse hatches, ‘K’ – arrow with hatches, ‘T’ – triangle, ‘S’ – square, ‘D’ – rhombus, ‘O’ – circle, ‘X’ – skew cross, ‘_’ – nothing (the default). The following rule applies: the first symbol specifies the arrow at the end of line, the second specifies the arrow at the beginning of the line. For example, ‘r-A’ defines a red solid line with usual arrow at the end, ‘b|AI’ defines a blue dash line with an arrow at the end and with hatches at the beginning, ‘_O’ defines a line with the current style and with a circle at the beginning. These styles are applicable during the graphics plotting as well (for example, 1D plotting).
-
The color scheme is used for determining the color of surfaces, isolines, isosurfaces and so on. The color scheme is defined by the string, which may contain several characters that are color id (see Line styles) or characters ‘#:|’. Symbol ‘#’ switches to mesh drawing or to a wire plot. Symbol ‘|’ disables color interpolation in color scheme, which can be useful, for example, for sharp colors during matrix plotting. Symbol ‘:’ terminate the color scheme parsing. Following it, the user may put styles for the text, rotation axis for curves/isocontours, and so on. Color scheme may contain up to 32 color values.
-
-
The final color is a linear interpolation of color array. The color array is constructed from the string ids (including “bright” colors, see Color styles). The argument is the amplitude normalized in color range (see Axis settings). For example, string containing 4 characters ‘bcyr’ corresponds to a colorbar from blue (lowest value) through cyan (next value) through yellow (next value) to the red (highest value). String ‘kw’ corresponds to a colorbar from black (lowest value) to white (highest value). String ‘m’ corresponds to a simple magenta color.
-
-
The special 2-axis color scheme (like in map plot) can be used if it contain symbol ‘%’. In this case the second direction (alpha channel) is used as second coordinate for colors. At this, up to 4 colors can be specified for corners: {c1,a1}, {c2,a1}, {c1,a2}, {c2,a2}. Here color and alpha ranges are {c1,c2} and {a1,a2} correspondingly. If one specify less than 4 colors then black color is used for corner {c1,a1}. If only 2 colors are specified then the color of their sum is used for corner {c2,a2}.
-
-
There are several useful combinations. String ‘kw’ corresponds to the simplest gray color scheme where higher values are brighter. String ‘wk’ presents the inverse gray color scheme where higher value is darker. Strings ‘kRryw’, ‘kGgw’, ‘kBbcw’ present the well-known hot, summer and winter color schemes. Strings ‘BbwrR’ and ‘bBkRr’ allow to view bi-color figure on white or black background, where negative values are blue and positive values are red. String ‘BbcyrR’ gives a color scheme similar to the well-known jet color scheme.
-
-
For more precise coloring, you can change default (equidistant) position of colors in color scheme. The format is ‘{CN,pos}’, ‘{CN,pos}’ or ‘{xRRGGBB,pos}’. The position value pos should be in range [0, 1]. Note, that alternative method for fine tuning of the color scheme is using the formula for coloring (see Curved coordinates).
-
-
-
-
When coloring by coordinate (used in map), the final color is determined by the position of the point in 3d space and is calculated from formula c=x*c[1] + y*c[2]. Here, c[1], c[2] are the first two elements of color array; x, y are normalized to axis range coordinates of the point.
-
-
Additionally, MathGL can apply mask to face filling at bitmap rendering. The kind of mask is specified by one of symbols ‘-+=;oOsS~<>jdD*^’ in color scheme. Mask can be rotated by arbitrary angle by command mask or by three predefined values +45, -45 and 90 degree by symbols ‘\/I’ correspondingly. Examples of predefined masks are shown on the figure below.
-
-
-
-
However, you can redefine mask for one symbol by specifying new matrix of size 8*8 as second argument for mask command. For example, the right-down subplot on the figure above is produced by code
-gr->SetMask('+', "ff00182424f800"); gr->Dens(a,"3+");
-or just use manual mask style (for v.2.3 and later)
-gr->Dens(a,"3{s00ff00182424f800}");
-
Text style is specified by the string which may contain: color id characters ‘wkrgbcymhRGBCYMHW’ (see Color styles), and font style (‘ribwou’) and/or alignment (‘LRC’) specifications. At this, font style and alignment begin after the separator ‘:’. For example, ‘r:iCb’ sets the bold (‘b’) italic (‘i’) font text aligned at the center (‘C’) and with red color (‘r’). Starting from MathGL v.2.3, you can set not single color for whole text, but use color gradient for printed text (see Color scheme).
-
-
The font styles are: ‘r’ – roman (or regular) font, ‘i’ – italic style, ‘b’ – bold style. By default roman roman font is used. The align types are: ‘L’ – align left (default), ‘C’ – align center, ‘R’ – align right, ‘T’ – align under, ‘V’ – align center vertical. Additional font effects are: ‘w’ – wired, ‘o’ – over-lined, ‘u’ – underlined.
-
-
Also a parsing of the LaTeX-like syntax is provided. There are commands for the font style changing inside the string (for example, use \b for bold font): \a or \overline – over-lined, \b or \textbf – bold, \i or \textit – italic, \r or \textrm – roman (disable bold and italic attributes), \u or \underline – underlined, \w or \wire – wired, \big – bigger size, @ – smaller size. The lower and upper indexes are specified by ‘_’ and ‘^’ symbols. At this the changed font style is applied only on next symbol or symbols in braces {}. The text in braces {} are treated as single symbol that allow one to print the index of index. For example, compare the strings ‘sin (x^{2^3})’ and ‘sin (x^2^3)’. You may also change text color inside string by command #? or by \color? where ‘?’ is symbolic id of the color (see Color styles). For example, words ‘blue’ and ‘red’ will be colored in the string ‘#b{blue} and \colorr{red} text’. The most of functions understand the newline symbol ‘\n’ and allows to print multi-line text. Finally, you can use arbitrary (if it was defined in font-face) UTF codes by command \utf0x????. For example, \utf0x3b1 will produce
- α symbol.
-
-
The most of commands for special TeX or AMSTeX symbols, the commands for font style changing (\textrm, \textbf, \textit, \textsc, \overline, \underline), accents (\hat, \tilde, \dot, \ddot, \acute, \check, \grave, \bar, \breve) and roots (\sqrt, \sqrt3, \sqrt4) are recognized. The full list contain approximately 2000 commands. Note that first space symbol after the command is ignored, but second one is printed as normal symbol (space). For example, the following strings produce the same result \tilde a: ‘\tilde{a}’; ‘\tilde a’; ‘\tilde{}a’.
-
-In particular, the Greek letters are recognizable special symbols: α – \alpha, β – \beta, γ – \gamma, δ – \delta, ε – \epsilon, η – \eta, ι – \iota, χ – \chi, κ – \kappa, λ – \lambda, μ – \mu, ν – \nu, o – \o, ω – \omega, ϕ – \phi, π – \pi, ψ – \psi, ρ – \rho, σ – \sigma, θ – \theta, τ – \tau, υ – \upsilon, ξ – \xi, ζ – \zeta, ς – \varsigma, ɛ – \varepsilon, ϑ – \vartheta, φ – \varphi, ϰ – \varkappa; A – \Alpha, B – \Beta, Γ – \Gamma, Δ – \Delta, E – \Epsilon, H – \Eta, I – \Iota, C – \Chi, K – \Kappa, Λ – \Lambda, M – \Mu, N – \Nu, O – \O, Ω – \Omega, Φ – \Phi, Π – \Pi, Ψ – \Psi, R – \Rho, Σ – \Sigma, Θ – \Theta, T – \Tau, Υ – \Upsilon, Ξ – \Xi, Z – \Zeta.
-
-
The font size can be defined explicitly (if size>0) or relatively to a base font size as |size|*FontSize (if size<0). The value size=0 specifies that the string will not be printed. The base font size is measured in internal “MathGL” units. Special functions SetFontSizePT(), SetFontSizeCM(), SetFontSizeIN() (see Font settings) allow one to set it in more “common” variables for a given dpi value of the picture.
-
MathGL have the fast variant of textual formula evaluation
-(see Evaluate expression)
-. There are a lot of functions and operators available. The operators are: ‘+’ – addition, ‘-’ – subtraction, ‘*’ – multiplication, ‘/’ – division, ‘%’ – modulo, ‘^’ – integer power. Also there are logical “operators”: ‘<’ – true if x<y, ‘>’ – true if x>y, ‘=’ – true if x=y, ‘&’ – true if x and y both nonzero, ‘|’ – true if x or y nonzero. These logical operators have lowest priority and return 1 if true or 0 if false.
-
-
The basic functions are: ‘sqrt(x)’ – square root of x, ‘pow(x,y)’ – power x in y, ‘ln(x)’ – natural logarithm of x, ‘lg(x)’ – decimal logarithm of x, ‘log(a,x)’ – logarithm base a of x, ‘abs(x)’ – absolute value of x, ‘sign(x)’ – sign of x, ‘mod(x,y)’ – x modulo y, ‘step(x)’ – step function, ‘int(x)’ – integer part of x, ‘rnd’ – random number, ‘random(x)’ – random data of size as in x, ‘hypot(x,y)’=sqrt(x^2+y^2) – hypotenuse, ‘cmplx(x,y)’=x+i*y – complex number, ‘pi’ – number
-π = 3.1415926…, inf=∞
-
-
Functions for complex numbers ‘real(x)’, ‘imag(x)’, ‘abs(x)’, ‘arg(x)’, ‘conj(x)’.
-
There are a set of special functions: ‘gamma(x)’ – Gamma function Γ(x) = ∫0∞ tx-1 exp(-t) dt, ‘gamma_inc(x,y)’ – incomplete Gamma function Γ(x,y) = ∫y∞ tx-1 exp(-t) dt, ‘psi(x)’ – digamma function ψ(x) = Γ′(x)/Γ(x) for x≠0, ‘ai(x)’ – Airy function Ai(x), ‘bi(x)’ – Airy function Bi(x), ‘cl(x)’ – Clausen function, ‘li2(x)’ (or ‘dilog(x)’) – dilogarithm Li2(x) = -ℜ∫0xds log(1-s)/s, ‘sinc(x)’ – compute sinc(x) = sin(πx)/(πx) for any value of x, ‘zeta(x)’ – Riemann zeta function ζ(s) = ∑k=1∞k-s for arbitrary s≠1, ‘eta(x)’ – eta function η(s) = (1 - 21-s)ζ(s) for arbitrary s, ‘lp(l,x)’ – Legendre polynomial Pl(x), (|x|≤1, l≥0), ‘w0(x)’ – principal branch of the Lambert W function, ‘w1(x)’ – principal branch of the Lambert W function. Function W(x) is defined to be solution of the equation: W exp(W) = x.
-
-
The exponent integrals are: ‘ci(x)’ – Cosine integral Ci(x) = ∫0xdt cos(t)/t, ‘si(x)’ – Sine integral Si(x) = ∫0xdt sin(t)/t, ‘erf(x)’ – error function erf(x) = (2/√π) ∫0xdt exp(-t2) , ‘ei(x)’ – exponential integral Ei(x) = -PV(∫-x∞dt exp(-t)/t) (where PV denotes the principal value of the integral), ‘e1(x)’ – exponential integral E1(x) = ℜ∫1∞dt exp(-xt)/t, ‘e2(x)’ – exponential integral E2(x) = ℜ∫1∞dt exp(-xt)/t2, ‘ei3(x)’ – exponential integral Ei3(x) = ∫0xdt exp(-t3) for x≥0.
-
-
Bessel functions are: ‘j(nu,x)’ – regular cylindrical Bessel function of fractional order nu, ‘y(nu,x)’ – irregular cylindrical Bessel function of fractional order nu, ‘i(nu,x)’ – regular modified Bessel function of fractional order nu, ‘k(nu,x)’ – irregular modified Bessel function of fractional order nu.
-
-
Elliptic integrals are: ‘ee(k)’ – complete elliptic integral is denoted by E(k) = E(π/2,k), ‘ek(k)’ – complete elliptic integral is denoted by K(k) = F(π/2,k), ‘e(phi,k)’ – elliptic integral E(φ,k) = ∫0φdt √(1 - k2sin2(t)), ‘f(phi,k)’ – elliptic integral F(φ,k) = ∫0φdt 1/√(1 - k2sin2(t))
Note, some of these functions are unavailable if MathGL was compiled without GSL support.
-
-
There is no difference between lower or upper case in formulas. If argument value lie outside the range of function definition then function returns NaN.
-
Command options allow the easy setup of the selected plot by changing global settings only for this plot. Each option start from symbol ‘;’. Options work so that MathGL remember the current settings, change settings as it being set in the option, execute function and return the original settings back. So, the options are most usable for plotting functions.
-
-
The most useful options are xrange, yrange, zrange. They sets the boundaries for data change. This boundaries are used for automatically filled variables. So, these options allow one to change the position of some plots. For example, in command Plot(y,"","xrange 0.1 0.9"); or plot y; xrange 0.1 0.9 the x coordinate will be equidistantly distributed in range 0.1 ... 0.9. See Using options, for sample code and picture.
-
-
The full list of options are:
-
-
-
-
MGL option: alphaval
-
Sets alpha value (transparency) of the plot. The value should be in range [0, 1]. See also alphadef.
-
-
-
-
-
MGL option: xrangeval1 val2
-
Sets boundaries of x coordinate change for the plot. See also xrange.
-
-
-
-
MGL option: yrangeval1 val2
-
Sets boundaries of y coordinate change for the plot. See also yrange.
-
-
-
-
MGL option: zrangeval1 val2
-
Sets boundaries of z coordinate change for the plot. See also zrange.
-
-
-
-
-
MGL option: cutval
-
Sets whether to cut or to project the plot points lying outside the bounding box. See also cut.
-
Adds string ’txt’ to internal legend accumulator. The style of described line and mark is taken from arguments of the last 1D plotting command. See also legend.
-
-
-
-
MGL option: valueval
-
Set the value to be used as additional numeric parameter in plotting command.
-
The MathGL library has interfaces for a set of languages. Most of them are based on the C interface via SWIG tool. There are Python, Java, Octave, Lisp, C#, Guile, Lua, Modula 3, Ocaml, Perl, PHP, Pike, R, Ruby, and Tcl interfaces. Also there is a Fortran interface which has a similar set of functions, but slightly different types of arguments (integers instead of pointers). These functions are marked as [C function].
-
-
Some of the languages listed above support classes (like C++ or Python). The name of functions for them is the same as in C++ (see MathGL core and Data processing) and marked like [Method on mglGraph].
-
-
Finally, a special command language MGL (see MGL scripts) was written for a faster access to plotting functions. Corresponding scripts can be executed separately (by UDAV, mglconv, mglview and so on) or from the C/C++/Python/... code (see mglParse class).
-
The C interface is a base for many other interfaces. It contains the pure C functions for most of the methods of MathGL classes. In distinction to C++ classes, C functions must have an argument HMGL (for graphics) and/or HMDT (for data arrays), which specifies the object for drawing or manipulating (changing). So, firstly, the user has to create this object by the function mgl_create_*() and has to delete it after the use by function mgl_delete_*().
-
-
All C functions are described in the header file #include <mgl2/mgl_cf.h> and use variables of the following types:
-
-
HMGL — Pointer to class mglGraph (see MathGL core).
-
HCDT — Pointer to class const mglDataA (see Data processing) — constant data array.
-
HMDT — Pointer to class mglData (see Data processing) — data array of real numbers.
-
HADT — Pointer to class mglDataC (see Data processing) — data array of complex numbers.
-
HMPR — Pointer to class mglParse (see mglParse class) — MGL script parsing.
-
HMEX — Pointer to class mglExpr (see Evaluate expression) — textual formulas for real numbers.
-
HMAX — Pointer to class mglExprC (see Evaluate expression) — textual formulas for complex numbers.
-
-
These variables contain identifiers for graphics drawing objects and for the data objects.
-
-
Fortran functions/subroutines have the same names as C functions. However, there is a difference. Variable of type HMGL, HMDT must be an integer with sufficient size (integer*4 in the 32-bit operating system or integer*8 in the 64-bit operating system). All C functions of type void are subroutines in Fortran, which are called by operator call. The exceptions are functions, which return variables of types HMGL or HMDT. These functions should be declared as integer in Fortran code. Also, one should keep in mind that strings in Fortran are denoted by ' symbol, not the " symbol.
-
MathGL provides the interface to a set of languages via SWIG library. Some of these languages support classes. The typical example is Python – which is named in this chapter’s title. Exactly the same classes are used for high-level C++ API. Its feature is using only inline member-functions what make high-level API to be independent on compiler even for binary build.
-
-
There are 3 main classes in:
-
-
mglGraph
-– provide most plotting functions (see MathGL core).
-
mglData
-– provide base data processing (see Data processing). It have an additional feature to access data values. You can use a construct like this: dat[i]=sth; or sth=dat[i] where flat representation of data is used (i.e., i can be in range 0...nx*nx*nz-1). You can also import NumPy arrays as input arguments in Python: mgl_dat = mglData(numpy_dat);.
-
mglParse
-– provide functions for parsing MGL scripts (see MGL scripts).
-
-
-
-
To use Python classes just execute ‘import mathgl’. The simplest example will be:
-
The core of MathGL is mglGraph class defined in #include <mgl2/mgl.h>. It contains a lot of plotting functions for 1D, 2D and 3D data. It also encapsulates parameters for axes drawing. Moreover an arbitrary coordinate transformation can be used for each axis. All plotting functions use data encapsulated in mglData class (see Data processing) that allows to check sizes of used arrays easily. Also it have many functions for data handling: modify it by formulas, find momentums and distribution (histogram), apply operator (differentiate, integrate, transpose, Fourier and so on), change data sizes (interpolate, squeeze, crop and so on). Additional information about colors, fonts, formula parsing can be found in General concepts and Other classes.
-
-
Some of MathGL features will appear only in novel versions. To test used MathGL version you can use following function.
-
-
MGL command: version'ver'
-
Method on mglGraph: boolCheckVersion(const char *ver) static
-
C function: intmgl_check_version(const char *ver)
-
Return zero if MathGL version is appropriate for required by ver, i.e. if major version is the same and minor version is greater or equal to one in ver.
-
Constructor on mglGraph: mglGraph(int kind=0, int width=600, int height=400)
-
Constructor on mglGraph: mglGraph(const mglGraph &gr)
-
Constructor on mglGraph: mglGraph(HMGL gr)
-
C function: HMGLmgl_create_graph(int width, int height)
-
C function: HMGLmgl_create_graph_gl()
-
Creates the instance of class mglGraph with specified sizes width and height. Parameter kind may have following values: ‘0’ – use default plotter, ‘1’ – use OpenGL plotter.
-
-
-
-
Destructor on mglGraph: ~mglGraph()
-
C function: HMGLmgl_delete_graph(HMGL gr)
-
Deletes the instance of class mglGraph.
-
-
-
-
Method on mglGraph: HMGLSelf()
-
Returns the pointer to internal object of type HMGL.
-
Functions and variables in this group influences on overall graphics appearance. So all of them should be placed before any actual plotting function calls.
-
-
-
MGL command: reset
-
Method on mglGraph: voidDefaultPlotParam()
-
C function: voidmgl_set_def_param(HMGL gr)
-
Restore initial values for all of parameters and clear the image.
-
-
-
-
MGL command: setupval flag
-
Method on mglGraph: voidSetFlagAdv(int val, uint32_t flag)
-
C function: voidmgl_set_flag(HMGL gr, int val, uint32_t flag)
-
Sets the value of internal binary flag to val. The list of flags can be found at define.h. The current list of flags are:
-
#define MGL_ENABLE_CUT 0x00000004 ///< Flag which determines how points outside bounding box are drown.
-#define MGL_ENABLE_RTEXT 0x00000008 ///< Use text rotation along axis
-#define MGL_AUTO_FACTOR 0x00000010 ///< Enable autochange PlotFactor
-#define MGL_ENABLE_ALPHA 0x00000020 ///< Flag that Alpha is used
-#define MGL_ENABLE_LIGHT 0x00000040 ///< Flag of using lightning
-#define MGL_TICKS_ROTATE 0x00000080 ///< Allow ticks rotation
-#define MGL_TICKS_SKIP 0x00000100 ///< Allow ticks rotation
-#define MGL_DISABLE_SCALE 0x00000200 ///< Temporary flag for disable scaling (used for axis)
-#define MGL_FINISHED 0x00000400 ///< Flag that final picture (i.e. mglCanvas::G) is ready
-#define MGL_USE_GMTIME 0x00000800 ///< Use gmtime instead of localtime
-#define MGL_SHOW_POS 0x00001000 ///< Switch to show or not mouse click position
-#define MGL_CLF_ON_UPD 0x00002000 ///< Clear plot before Update()
-#define MGL_NOSUBTICKS 0x00004000 ///< Disable subticks drawing (for bounding box)
-#define MGL_LOCAL_LIGHT 0x00008000 ///< Keep light sources for each inplot
-#define MGL_VECT_FRAME 0x00010000 ///< Use DrwDat to remember all data of frames
-#define MGL_REDUCEACC 0x00020000 ///< Reduce accuracy of points (to reduce size of output files)
-#define MGL_PREFERVC 0x00040000 ///< Prefer vertex color instead of texture if output format supports
-#define MGL_ONESIDED 0x00080000 ///< Render only front side of surfaces if output format supports (for debugging)
-#define MGL_NO_ORIGIN 0x00100000 ///< Don't draw tick labels at axis origin
-#define MGL_GRAY_MODE 0x00200000 ///< Convert all colors to gray ones
-#define MGL_FULL_CURV 0x00400000 ///< Disable omitting points in straight-line part(s)
-#define MGL_NO_SCALE_REL 0x00800000 ///< Disable font scaling in relative inplots
-
-
-
-
C function: voidmgl_bsize(unsigned bsize)
-
Set buffer size for number of primitives as (1<<bsize)^2. I.e. as 10^12 for bsize=20 or 4*10^9 for bsize=16 (default). NOTE: you set it only once before any plotting. The current value is returned.
-
There are several functions and variables for setup transparency. The general function is alpha which switch on/off the transparency for overall plot. It influence only for graphics which created after alpha call (with one exception, OpenGL). Function alphadef specify the default value of alpha-channel. Finally, function transptype set the kind of transparency. See Transparency and lighting, for sample code and picture.
-
-
-
MGL command: alpha[val=on]
-
Method on mglGraph: voidAlpha(bool enable)
-
C function: voidmgl_set_alpha(HMGL gr, int enable)
-
Sets the transparency on/off and returns previous value of transparency. It is recommended to call this function before any plotting command. Default value is transparency off.
-
-
-
-
MGL command: alphadefval
-
Method on mglGraph: voidSetAlphaDef(mreal val)
-
C function: voidmgl_set_alpha_default(HMGL gr, mreal alpha)
-
Sets default value of alpha channel (transparency) for all plotting functions. Initial value is 0.5.
-
-
-
-
MGL command: transptypeval
-
Method on mglGraph: voidSetTranspType(int type)
-
C function: voidmgl_set_transp_type(HMGL gr, int type)
-
Set the type of transparency. Possible values are:
-
-
Normal transparency (‘0’) – below things is less visible than upper ones. It does not look well in OpenGL mode (mglGraphGL) for several surfaces.
-
Glass-like transparency (‘1’) – below and upper things are commutable and just decrease intensity of light by RGB channel.
-
Lamp-like transparency (‘2’) – below and upper things are commutable and are the source of some additional light. I recommend to set SetAlphaDef(0.3) or less for lamp-like transparency.
-
There are several functions for setup lighting. The general function is light which switch on/off the lighting for overall plot. It influence only for graphics which created after light call (with one exception, OpenGL). Generally MathGL support up to 10 independent light sources. But in OpenGL mode only 8 of light sources is used due to OpenGL limitations. The position, color, brightness of each light source can be set separately. By default only one light source is active. It is source number 0 with white color, located at top of the plot. See Lighting sample, for sample code and picture.
-
-
-
MGL command: light[val=on]
-
Method on mglGraph: boolLight(bool enable)
-
C function: voidmgl_set_light(HMGL gr, int enable)
-
Sets the using of light on/off for overall plot. Function returns previous value of lighting. Default value is lightning off.
-
-
-
-
MGL command: lightnumval
-
Method on mglGraph: voidLight(int n, bool enable)
-
C function: voidmgl_set_light_n(HMGL gr, int n, int enable)
Method on mglGraph: voidAddLight(int n, mglPoint d, char c='w', mreal bright=0.5, mreal ap=0)
-
Method on mglGraph: voidAddLight(int n, mglPoint r, mglPoint d, char c='w', mreal bright=0.5, mreal ap=0)
-
C function: voidmgl_add_light(HMGL gr, int n, mreal dx, mreal dy, mreal dz)
-
C function: voidmgl_add_light_ext(HMGL gr, int n, mreal dx, mreal dy, mreal dz, char c, mreal bright, mreal ap)
-
C function: voidmgl_add_light_loc(HMGL gr, int n, mreal rx, mreal ry, mreal rz, mreal dx, mreal dy, mreal dz, char c, mreal bright, mreal ap)
-
The function adds a light source with identification n in direction d with color c and with brightness bright (which must be in range [0,1]). If position r is specified and isn’t NAN then light source is supposed to be local otherwise light source is supposed to be placed at infinity.
-
-
-
-
MGL command: diffuseval
-
Method on mglGraph: voidSetDiffuse(mreal bright)
-
C function: voidmgl_set_difbr(HMGL gr, mreal bright)
-
Set brightness of diffusive light (only for local light sources).
-
-
-
-
MGL command: ambientval
-
Method on mglGraph: voidSetAmbient(mreal bright=0.5)
-
C function: voidmgl_set_ambbr(HMGL gr, mreal bright)
-
Sets the brightness of ambient light. The value should be in range [0,1].
-
-
-
-
MGL command: attachlightval
-
Method on mglGraph: voidAttachLight(bool val)
-
C function: voidmgl_set_attach_light(HMGL gr, int val)
-
Set to attach light settings to inplot/subplot. Note, OpenGL and some output formats don’t support this feature.
-
Method on mglGraph: voidFog(mreal d, mreal dz=0.25)
-
C function: voidmgl_set_fog(HMGL gr, mreal d, mreal dz)
-
Function imitate a fog in the plot. Fog start from relative distance dz from view point and its density growths exponentially in depth. So that the fog influence is determined by law ~ 1-exp(-d*z). Here z is normalized to 1 depth of the plot. If value d=0 then the fog is absent. Note, that fog was applied at stage of image creation, not at stage of drawing. See Adding fog, for sample code and picture.
-
These variables control the default (initial) values for most graphics parameters including sizes of markers, arrows, line width and so on. As any other settings these ones will influence only on plots created after the settings change.
-
-
-
MGL command: barwidthval
-
Method on mglGraph: voidSetBarWidth( mreal val)
-
C function: voidmgl_set_bar_width(HMGL gr, mreal val)
C function: voidmgl_set_mark_size(HMGL gr, mreal val)
-
Sets size of marks for 1D plotting. Default value is 1.
-
-
-
-
MGL command: arrowsizeval
-
Method on mglGraph: voidSetArrowSize(mreal val)
-
C function: voidmgl_set_arrow_size(HMGL gr, mreal val)
-
Sets size of arrows for 1D plotting, lines and curves (see Primitives). Default value is 1.
-
-
-
-
MGL command: meshnumval
-
Method on mglGraph: voidSetMeshNum(int val)
-
C function: voidmgl_set_meshnum(HMGL gr, int num)
-
Sets approximate number of lines in mesh, fall, grid2, and also the number of hachures in vect, dew, and the number of cells in cloud, and the number of markers in plot, tens, step, mark, textmark. By default (=0) it draws all lines/hachures/cells/markers.
-
-
-
-
MGL command: facenumval
-
Method on mglGraph: voidSetFaceNum(int val)
-
C function: voidmgl_set_facenum(HMGL gr, int num)
-
Sets approximate number of visible faces. Can be used for speeding up drawing by cost of lower quality. By default (=0) it draws all of them.
-
-
-
-
MGL command: plotid'id'
-
Method on mglGraph: voidSetPlotId(const char *id)
-
C function: voidmgl_set_plotid(HMGL gr, const char *id)
-
Sets default name id as filename for saving (in FLTK window for example).
-
-
-
-
Method on mglGraph: const char *GetPlotId()
-
C function only: const char *mgl_get_plotid(HMGL gr)
-
Fortran subroutine: mgl_get_plotid(long gr, char *out, int len)
-
Gets default name id as filename for saving (in FLTK window for example).
-
-
-
-
MGL command: pendeltaval
-
Method on mglGraph: voidSetPenDelta(double val)
-
C function: voidmgl_pen_delta(HMGL gr, double val)
-
Changes the blur around lines and text (default is 1). For val>1 the text and lines are more sharped. For val<1 the text and lines are more blurred.
-
These variables and functions set the condition when the points are excluded (cutted) from the drawing. Note, that a point with NAN value(s) of coordinate or amplitude will be automatically excluded from the drawing. See Cutting sample, for sample code and picture.
-
-
-
MGL command: cutval
-
Method on mglGraph: voidSetCut(bool val)
-
C function: voidmgl_set_cut(HMGL gr, int val)
-
Flag which determines how points outside bounding box are drawn. If it is true then points are excluded from plot (it is default) otherwise the points are projected to edges of bounding box.
-
-
-
-
MGL command: cutx1 y1 z1 x2 y2 z2
-
Method on mglGraph: voidSetCutBox(mglPoint p1, mglPoint p1)
Lower and upper edge of the box in which never points are drawn. If both edges are the same (the variables are equal) then the cutting box is empty.
-
-
-
-
MGL command: cut'cond'
-
Method on mglGraph: voidCutOff(const char *cond)
-
C function: voidmgl_set_cutoff(HMGL gr, const char *cond)
-
Sets the cutting off condition by formula cond. This condition determine will point be plotted or not. If value of formula is nonzero then point is omitted, otherwise it plotted. Set argument as "" to disable cutting off condition.
-
Font style for text and labels (see text). Initial style is ’fnt’=’:rC’ give Roman font with centering. Parameter val sets the size of font for tick and axis labels. Default font size of axis labels is 1.4 times large than for tick labels. For more detail, see Font styles.
-
-
-
-
MGL command: rotatetextval
-
Method on mglGraph: voidSetRotatedText(bool val)
-
C function: voidmgl_set_rotated_text(HMGL gr, int val)
-
Sets to use or not text rotation.
-
-
-
-
MGL command: scaletextval
-
Method on mglGraph: voidSetScaleText(bool val)
-
C function: voidmgl_set_scale_text(HMGL gr, int val)
Method on mglGraph: voidSetPalette(const char *colors)
-
C function: voidmgl_set_palette(HMGL gr, const char *colors)
-
Sets the palette as selected colors. Default value is "Hbgrcmyhlnqeup" that corresponds to colors: dark gray ‘H’, blue ‘b’, green ‘g’, red ‘r’, cyan ‘c’, magenta ‘m’, yellow ‘y’, gray ‘h’, blue-green ‘l’, sky-blue ‘n’, orange ‘q’, yellow-green ‘e’, blue-violet ‘u’, purple ‘p’. The palette is used mostly in 1D plots (see 1D plotting) for curves which styles are not specified. Internal color counter will be nullified by any change of palette. This includes even hidden change (for example, by box or axis functions).
-
-
-
-
Method on mglGraph: voidSetDefScheme(const char *sch)
-
C function: voidmgl_set_def_sch(HMGL gr, const char *sch)
-
Sets the sch as default color scheme. Default value is "BbcyrR".
-
-
-
-
Method on mglGraph: voidSetColor(char id, mreal r, mreal g, mreal b) static
-
C function: voidmgl_set_color(char id, mreal r, mreal g, mreal b)
-
Sets RGB values for color with given id. This is global setting which influence on any later usage of symbol id.
-
Method on mglGraph: voidSetMask(char id, const char *hex)
-
Method on mglGraph: voidSetMask(char id, uint64_t hex)
-
C function: voidmgl_set_mask(HMGL gr, const char *hex)
-
C function: voidmgl_set_mask_val(HMGL gr, uint64_t hex)
-
Sets new bit matrix hex of size 8*8 for mask with given id. This is global setting which influence on any later usage of symbol id. The predefined masks are (see Color scheme): ‘-’ give lines (0x000000FF00000000), ‘+’ give cross-lines (080808FF08080808), ‘=’ give double lines (0000FF00FF000000), ‘;’ give dash lines (0x0000000F00000000), ‘o’ give circles (0000182424180000), ‘O’ give filled circles (0000183C3C180000), ‘s’ give squares (00003C24243C0000), ‘S’ give solid squares (00003C3C3C3C0000), ‘~’ give waves (0000060990600000), ‘<’ give left triangles (0060584658600000), ‘>’ give right triangles (00061A621A060000), ‘j’ give dash-dot lines (0000002700000000), ‘d’ give pluses (0x0008083E08080000), ‘D’ give tacks (0x0139010010931000), ‘*’ give dots (0x0000001818000000), ‘^’ give bricks (0x101010FF010101FF). Parameter angle set the rotation angle too. IMPORTANT: the rotation angle will be replaced by a multiple of 45 degrees at export to EPS.
-
-
-
-
MGL command: maskangle
-
Method on mglGraph: voidSetMaskAngle(int angle)
-
C function: voidmgl_set_mask_angle(HMGL gr, int angle)
-
Sets the default rotation angle (in degrees) for masks. Note, you can use symbols ‘\’, ‘/’, ‘I’ in color scheme for setting rotation angles as 45, -45 and 90 degrees correspondingly. IMPORTANT: the rotation angle will be replaced by a multiple of 45 degrees at export to EPS.
-
Normally user should set it to zero by SetWarn(0); before plotting and check if GetWarn() or Message() return non zero after plotting. Only last warning will be saved. All warnings/errors produced by MathGL is not critical – the plot just will not be drawn. By default, all warnings are printed in stderr. You can disable it by using mgl_suppress_warn(true);.
-
-
-
Method on mglGraph: voidSetWarn(int code, const char *info="")
-
C function: voidmgl_set_warn(HMGL gr, int code, const char *info)
-
Set warning code. Normally you should call this function only for clearing the warning state, i.e. call SetWarn(0);. Text info will be printed as is if code<0.
-
-
-
-
Method on mglGraph: const char *Message()
-
C function only: const char *mgl_get_mess(HMGLgr)
-
Fortran subroutine: mgl_get_mess(long gr, char *out, int len)
-
Return messages about matters why some plot are not drawn. If returned string is empty then there are no messages.
-
-
-
-
Method on mglGraph: intGetWarn()
-
C function: intmgl_get_warn(HMGL gr)
-
Return the numerical ID of warning about the not drawn plot. Possible values are:
-
-
mglWarnNone=0
-
Everything OK
-
-
mglWarnDim
-
Data dimension(s) is incompatible
-
-
mglWarnLow
-
Data dimension(s) is too small
-
-
mglWarnNeg
-
Minimal data value is negative
-
-
mglWarnFile
-
No file or wrong data dimensions
-
-
mglWarnMem
-
Not enough memory
-
-
mglWarnZero
-
Data values are zero
-
-
mglWarnLeg
-
No legend entries
-
-
mglWarnSlc
-
Slice value is out of range
-
-
mglWarnCnt
-
Number of contours is zero or negative
-
-
mglWarnOpen
-
Couldn’t open file
-
-
mglWarnLId
-
Light: ID is out of range
-
-
mglWarnSize
-
Setsize: size(s) is zero or negative
-
-
mglWarnFmt
-
Format is not supported for that build
-
-
mglWarnTern
-
Axis ranges are incompatible
-
-
mglWarnNull
-
Pointer is NULL
-
-
mglWarnSpc
-
Not enough space for plot
-
-
mglScrArg
-
Wrong argument(s) of a command in MGL script
-
-
mglScrCmd
-
Wrong command in MGL script
-
-
mglScrLong
-
Too long line in MGL script
-
-
mglScrStr
-
Unbalanced ’ in MGL script
-
-
mglScrTemp
-
Change temporary data in MGL script
-
-
-
-
-
-
Method on mglGraph: voidSuppressWarn(bool state) static
-
C function: voidmgl_suppress_warn(int state)
-
Disable printing warnings to stderr if state is nonzero.
-
-
-
-
Method on mglGraph: voidSetGlobalWarn(const char *info) static
-
C function: voidmgl_set_global_warn(const char *info)
-
Set warning message info for global scope.
-
-
-
-
Method on mglGraph: const char *GlobalWarn() static
C function only: voidmgl_ask_stop(HMGL gr, int stop)
-
Ask to stop drawing if stop is non-zero, otherwise reset stop flag.
-
-
-
-
Method on mglGraph: boolNeedStop()
-
C function only: voidmgl_need_stop(HMGL gr)
-
Return true if drawing should be terminated. Also it process all events in GUI. User should call this function from time to time inside a long calculation to allow processing events for GUI.
-
-
-
-
Method on mglGraph: boolSetEventFunc(void (*func)(void *), void *par=NULL)
-
C function only: voidmgl_set_event_func(HMGL gr, void (*func)(void *), void *par)
-
Set callback function which will be called to process events of GUI library.
-
These large set of variables and functions control how the axis and ticks will be drawn. Note that there is 3-step transformation of data coordinates are performed. Firstly, coordinates are projected if Cut=true (see Cutting), after it transformation formulas are applied, and finally the data was normalized in bounding box. Note, that MathGL will produce warning if axis range and transformation formulas are not compatible.
-
Method on mglGraph: voidSetRange(char dir, mreal v1, mreal v2)
-
Method on mglGraph: voidAddRange(char dir, mreal v1, mreal v2)
-
C function: voidmgl_set_range_val(HMGL gr, char dir, mreal v1, mreal v2)
-
C function: voidmgl_add_range_val(HMGL gr, char dir, mreal v1, mreal v2)
-
Sets or adds the range for ‘x’-,‘y’-,‘z’- coordinate or coloring (‘c’). If one of values is NAN then it is ignored. See also ranges.
-
-
-
-
-
MGL command: xrangedat [add=off]
-
MGL command: yrangedat [add=off]
-
MGL command: zrangedat [add=off]
-
MGL command: crangedat [add=off]
-
Method on mglGraph: voidSetRange(char dir, const mglDataA &dat, bool add=false)
-
C function: voidmgl_set_range_dat(HMGL gr, char dir, const HCDT a, int add)
-
Sets the range for ‘x’-,‘y’-,‘z’- coordinate or coloring (‘c’) as minimal and maximal values of data dat. Parameter add=on shows that the new range will be joined to existed one (not replace it).
-
-
-
-
MGL command: rangesx1 x2 y1 y2 [z1=0 z2=0]
-
Method on mglGraph: voidSetRanges(mglPoint p1, mglPoint p2)
Sets the ranges of coordinates. If minimal and maximal values of the coordinate are the same then they are ignored. Also it sets the range for coloring (analogous to crange z1 z2). This is default color range for 2d plots. Initial ranges are [-1, 1].
-
-
-
-
MGL command: rangesxx yy [zz cc=zz]
-
Method on mglGraph: voidSetRanges(const mglDataA &xx, const mglDataA &yy)
Additionally extend axis range for any settings made by SetRange or SetRanges functions according the formula min += (max-min)*p1 and max += (max-min)*p1 (or min *= (max/min)^p1 and max *= (max/min)^p1 for log-axis range when inf>max/min>100 or 0<max/min<0.01). Initial ranges are [0, 1]. Attention! this settings can not be overwritten by any other functions, including DefaultPlotParam().
-
Sets transformation formulas for curvilinear coordinate. Each string should contain mathematical expression for real coordinate depending on internal coordinates ‘x’, ‘y’, ‘z’ and ‘a’ or ‘c’ for colorbar. For example, the cylindrical coordinates are introduced as SetFunc("x*cos(y)", "x*sin(y)", "z");. For removing of formulas the corresponding parameter should be empty or NULL. Using transformation formulas will slightly slowing the program. Parameter EqA set the similar transformation formula for color scheme. See Textual formulas.
-
-
-
-
MGL command: axishow
-
Method on mglGraph: voidSetCoor(int how)
-
C function: voidmgl_set_coor(HMGL gr, int how)
-
Sets one of the predefined transformation formulas for curvilinear coordinate. Parameter how define the coordinates:
-
-
mglCartesian=0
-
Cartesian coordinates (no transformation, {x,y,z});
-
C function: voidmgl_set_ternary(HMGL gr, int tern)
-
The function sets to draws Ternary (tern=1), Quaternary (tern=2) plot or projections (tern=4,5,6).
-
-
Ternary plot is special plot for 3 dependent coordinates (components) a, b, c so that a+b+c=1. MathGL uses only 2 independent coordinates a=x and b=y since it is enough to plot everything. At this third coordinate z act as another parameter to produce contour lines, surfaces and so on.
-
-
Correspondingly, Quaternary plot is plot for 4 dependent coordinates a, b, c and d so that a+b+c+d=1. MathGL uses only 3 independent coordinates a=x, b=y and d=z since it is enough to plot everything.
-
-
Projections can be obtained by adding value 4 to tern argument. So, that tern=4 will draw projections in Cartesian coordinates, tern=5 will draw projections in Ternary coordinates, tern=6 will draw projections in Quaternary coordinates. If you add 8 instead of 4 then all text labels will not be printed on projections.
-
-
Use Ternary(0) for returning to usual axis. See Ternary axis, for sample code and picture. See Axis projection, for sample code and picture.
-
Method on mglGraph: voidAdjust(const char *dir="xyzc")
-
C function: voidmgl_adjust_ticks(HMGL gr, const char *dir)
-
Set the ticks step, number of sub-ticks and initial ticks position to be the most human readable for the axis along direction(s) dir. Also set SetTuneTicks(true). Usually you don’t need to call this function except the case of returning to default settings.
-
-
-
-
MGL command: xtickval [sub=0 org=nan 'fact'='']
-
MGL command: ytickval [sub=0 org=nan 'fact'='']
-
MGL command: ztickval [sub=0 org=nan 'fact'='']
-
MGL command: xtickval sub ['fact'='']
-
MGL command: ytickval sub ['fact'='']
-
MGL command: ztickval sub ['fact'='']
-
MGL command: ctickval ['fact'='']
-
Method on mglGraph: voidSetTicks(char dir, mreal d=0, int ns=0, mreal org=NAN, const char *fact="")
-
Method on mglGraph: voidSetTicks(char dir, mreal d, int ns, mreal org, const wchar_t *fact)
-
C function: voidmgl_set_ticks(HMGL gr, char dir, mreal d, int ns, mreal org)
-
C function: voidmgl_set_ticks_fact(HMGL gr, char dir, mreal d, int ns, mreal org, const char *fact)
-
C function: voidmgl_set_ticks_factw(HMGL gr, char dir, mreal d, int ns, mreal org, const wchar_t *fact)
-
Set the ticks step d, number of sub-ticks ns (used for positive d) and initial ticks position org for the axis along direction dir (use ’c’ for colorbar ticks). Variable d set step for axis ticks (if positive) or it’s number on the axis range (if negative). Zero value set automatic ticks. If org value is NAN then axis origin is used. Parameter fact set text which will be printed after tick label (like "\pi" for d=M_PI).
-
-
-
-
MGL command: xtickval1 'lbl1' [val2 'lbl2' ...]
-
MGL command: ytickval1 'lbl1' [val2 'lbl2' ...]
-
MGL command: ztickval1 'lbl1' [val2 'lbl2' ...]
-
MGL command: ctickval1 'lbl1' [val2 'lbl2' ...]
-
MGL command: xtickvdat 'lbls' [add=off]
-
MGL command: ytickvdat 'lbls' [add=off]
-
MGL command: ztickvdat 'lbls' [add=off]
-
MGL command: ctickvdat 'lbls' [add=off]
-
Method on mglGraph: voidSetTicksVal(char dir, const char *lbl, bool add=false)
-
Method on mglGraph: voidSetTicksVal(char dir, const wchar_t *lbl, bool add=false)
Set the manual positions val and its labels lbl for ticks along axis dir. If array val is absent then values equidistantly distributed in x-axis range are used. Labels are separated by ‘\n’ symbol. If only one value is specified in MGL command then the label will be add to the current ones. Use SetTicks() to restore automatic ticks.
-
-
-
-
Method on mglGraph: voidAddTick(char dir, double val, const char *lbl)
-
Method on mglGraph: voidAddTick(char dir, double val, const wchar_t *lbl)
The same as previous but add single tick label lbl at position val to the list of existed ones.
-
-
-
-
MGL command: xtick'templ'
-
MGL command: ytick'templ'
-
MGL command: ztick'templ'
-
MGL command: ctick'templ'
-
Method on mglGraph: voidSetTickTempl(char dir, const char *templ)
-
Method on mglGraph: voidSetTickTempl(char dir, const wchar_t *templ)
-
C function: voidmgl_set_tick_templ(HMGL gr, const char *templ)
-
C function: voidmgl_set_tick_templw(HMGL gr, const wchar_t *templ)
-
Set template templ for x-,y-,z-axis ticks or colorbar ticks. It may contain TeX symbols also. If templ="" then default template is used (in simplest case it is ‘%.2g’). If template start with ‘&’ symbol then long integer value will be passed instead of default type double. Setting on template switch off automatic ticks tuning.
-
-
-
-
MGL command: ticktime'dir' [dv=0 'tmpl'='']
-
Method on mglGraph: voidSetTicksTime(char dir, mreal val, const char *templ)
-
C function: voidmgl_set_ticks_time(HMGL gr, mreal val, const char *templ)
-
Sets time labels with step val and template templ for x-,y-,z-axis ticks or colorbar ticks. It may contain TeX symbols also. The format of template templ is the same as described in http://www.manpagez.com/man/3/strftime/. Most common variants are ‘%X’ for national representation of time, ‘%x’ for national representation of date, ‘%Y’ for year with century. If val=0 and/or templ="" then automatic tick step and/or template will be selected. You can use mgl_get_time() function for obtaining number of second for given date/time string. Note, that MS Visual Studio couldn’t handle date before 1970.
-
-
-
-
C function: doublemgl_get_time(const char*str, const char *templ)
-
Gets number of seconds from 1970 year to specified date/time str. The format of string is specified by templ, which is the same as described in http://www.manpagez.com/man/3/strftime/. Most common variants are ‘%X’ for national representation of time, ‘%x’ for national representation of date, ‘%Y’ for year with century. Note, that MS Visual Studio couldn’t handle date before 1970.
-
-
-
-
MGL command: tuneticksval [pos=1.15]
-
Method on mglGraph: voidSetTuneTicks(int tune, mreal pos=1.15)
-
C function: voidmgl_tune_ticks(HMGL gr, int tune, mreal pos)
-
Switch on/off ticks enhancing by factoring common multiplier (for small, like from 0.001 to 0.002, or large, like from 1000 to 2000, coordinate values – enabled if tune&1 is nonzero) or common component (for narrow range, like from 0.999 to 1.000 – enabled if tune&2 is nonzero). Also set the position pos of common multiplier/component on the axis: =0 at minimal axis value, =1 at maximal axis value. Default value is 1.15.
-
The line style of axis (stl), ticks (tck) and subticks (sub). If stl is empty then default style is used (‘k’ or ‘w’ depending on transparency type). If tck or sub is empty then axis style is used (i.e. stl).
-
These functions control how and where further plotting will be placed. There is a certain calling order of these functions for the better plot appearance. First one should be subplot, multiplot or inplot for specifying the place. Second one can be title for adding title for the subplot. After it a rotate, shear and aspect. And finally any other plotting functions may be called. Alternatively you can use columnplot, gridplot, stickplot, shearplot or relative inplot for positioning plots in the column (or grid, or stick) one by another without gap between plot axis (bounding boxes). See Subplots, for sample code and picture.
-
-
-
MGL command: subplotnx ny m ['stl'='<>_^' dx=0 dy=0]
-
Method on mglGraph: voidSubPlot(int nx, int ny, int m, const char *stl="<>_^", mreal dx=0, mreal dy=0)
-
C function: voidmgl_subplot(HMGL gr, int nx, int ny, int m, const char *stl)
-
C function: voidmgl_subplot_d(HMGL gr, int nx, int ny, int m, const char *stl, mreal dx, mreal dy)
-
Puts further plotting in a m-th cell of nx*ny grid of the whole frame area. The position of the cell can be shifted from its default position by relative size dx, dy. This function set off any aspects or rotations. So it should be used first for creating the subplot. Extra space will be reserved for axis/colorbar if stl contain:
-
-
‘L’ or ‘<’ – at left side,
-
‘R’ or ‘>’ – at right side,
-
‘A’ or ‘^’ – at top side,
-
‘U’ or ‘_’ – at bottom side,
-
‘#’ – reserve none space (use whole region for axis range) – axis and tick labels will be invisible by default.
-
-
From the aesthetical point of view it is not recommended to use this function with different matrices in the same frame. Note, colorbar can be invisible (be out of image borders) if you set empty style ‘’.
-
-
-
-
MGL command: multiplotnx ny m dx dy ['style'='<>_^' sx sy]
-
Method on mglGraph: voidMultiPlot(int nx, int ny, int m, int dx, int dy, const char *stl="<>_^")
-
C function: voidmgl_multiplot(HMGL gr, int nx, int ny, int m, int dx, int dy, const char *stl)
-
Puts further plotting in a rectangle of dx*dy cells starting from m-th cell of nx*ny grid of the whole frame area. The position of the rectangular area can be shifted from its default position by relative size sx, sy. This function set off any aspects or rotations. So it should be used first for creating subplot. Extra space will be reserved for axis/colorbar if stl contain:
-
-
‘L’ or ‘<’ – at left side,
-
‘R’ or ‘>’ – at right side,
-
‘A’ or ‘^’ – at top side,
-
‘U’ or ‘_’ – at bottom side.
-‘#’ – reserve none space (use whole region for axis range) – axis and tick labels will be invisible by default.
-
Puts further plotting in some region of the whole frame surface. This function allows one to create a plot in arbitrary place of the screen. The position is defined by rectangular coordinates [x1, x2]*[y1, y2]. The coordinates x1, x2, y1, y2 are normalized to interval [0, 1]. If parameter rel=true then the relative position to current subplot (or inplot with rel=false) is used. This function set off any aspects or rotations. So it should be used first for creating subplot.
-
-
-
-
MGL command: columnplotnum ind [d=0]
-
Method on mglGraph: voidColumnPlot(int num, int ind, mreal d=0)
-
C function: voidmgl_columnplot(HMGL gr, int num, int ind)
-
C function: voidmgl_columnplot_d(HMGL gr, int num, int ind, mreal d)
-
Puts further plotting in ind-th cell of column with num cells. The position is relative to previous subplot (or inplot with rel=false). Parameter d set extra gap between cells.
-
-
-
-
MGL command: gridplotnx ny ind [d=0]
-
Method on mglGraph: voidGridPlot(int nx, int ny, int ind, mreal d=0)
-
C function: voidmgl_gridplot(HMGL gr, int nx, int ny, int ind)
-
C function: voidmgl_gridplot_d(HMGL gr, int nx, int ny, int ind, mreal d)
-
Puts further plotting in ind-th cell of nx*ny grid. The position is relative to previous subplot (or inplot with rel=false). Parameter d set extra gap between cells.
-
-
-
-
MGL command: stickplotnum ind tet phi
-
Method on mglGraph: voidStickPlot(int num, int ind, mreal tet, mreal phi)
-
C function: voidmgl_stickplot(HMGL gr, int num, int ind, mreal tet, mreal phi)
-
Puts further plotting in ind-th cell of stick with num cells. At this, stick is rotated on angles tet, phi. The position is relative to previous subplot (or inplot with rel=false).
-
-
-
-
MGL command: shearplotnum ind sx sy [xd yd]
-
Method on mglGraph: voidShearPlot(int num, int ind, mreal sx, mreal sy, mreal xd=1, mreal yd=0)
-
C function: voidmgl_shearplot(HMGL gr, int num, int ind, mreal sx, mreal sy, mreal xd, mreal yd)
-
Puts further plotting in ind-th cell of stick with num cells. At this, cell is sheared on values sx, sy. Stick direction is specified be xd and yd. The position is relative to previous subplot (or inplot with rel=false).
-
Parameter size set font size. This function set off any aspects or rotations. So it should be used just after creating subplot.
-
-
-
-
MGL command: rotatetetx tetz [tety=0]
-
Method on mglGraph: voidRotate(mreal TetX, mreal TetZ, mreal TetY=0)
-
C function: voidmgl_rotate(HMGL gr, mreal TetX, mreal TetZ, mreal TetY)
-
Rotates a further plotting relative to each axis {x, z, y} consecutively on angles TetX, TetZ, TetY.
-
-
-
-
MGL command: rotatetet x y z
-
Method on mglGraph: voidRotateN(mreal Tet, mreal x, mreal y, mreal z)
-
C function: voidmgl_rotate_vector(HMGL gr, mreal Tet, mreal x, mreal y, mreal z)
-
Rotates a further plotting around vector {x, y, z} on angle Tet.
-
-
-
-
MGL command: shearsx sy
-
Method on mglGraph: voidShear(mreal sx, mreal sy)
-
C function: voidmgl_shear(HMGL gr, mreal sx, mreal sy)
-
Shears a further plotting on values sx, sy.
-
-
-
-
MGL command: aspectax ay [az=1]
-
Method on mglGraph: voidAspect(mreal Ax, mreal Ay, mreal Az=1)
-
C function: voidmgl_aspect(HMGL gr, mreal Ax, mreal Ay, mreal Az)
-
Defines aspect ratio for the plot. The viewable axes will be related one to another as the ratio Ax:Ay:Az. For the best effect it should be used after rotate function. If Ax is NAN then function try to select optimal aspect ratio to keep equal ranges for x-y axis. At this, Ay will specify proportionality factor, or set to use automatic one if Ay=NAN.
-
-
-
-
-
Method on mglGraph: voidPush()
-
C function: voidmgl_mat_push(HMGL gr)
-
Push transformation matrix into stack. Later you can restore its current state by Pop() function.
-
-
-
-
Method on mglGraph: voidPop()
-
C function: voidmgl_mat_pop(HMGL gr)
-
Pop (restore last ’pushed’) transformation matrix into stack.
-
-
-
-
Method on mglGraph: voidSetPlotFactor(mreal val)
-
C function: voidmgl_set_plotfactor(HMGL gr, mreal val)
-
Sets the factor of plot size. It is not recommended to set it lower then 1.5. This is some analogue of function Zoom() but applied not to overall image but for each InPlot. Use negative value or zero to enable automatic selection.
-
-
-
-
There are 3 functions View(), Zoom() and Perspective() which transform whole image. I.e. they act as secondary transformation matrix. They were introduced for rotating/zooming the whole plot by mouse. It is not recommended to call them for picture drawing.
-
-
-
MGL command: perspectiveval
-
Method on mglGraph: voidPerspective(mreal a)
-
C function: voidmgl_perspective(HMGL gr, mreal a)
-
Add (switch on) the perspective to plot. The parameter a = Depth/(Depth+dz) \in [0,1). By default (a=0) the perspective is off.
-
-
-
-
MGL command: viewtetx tetz [tety=0]
-
Method on mglGraph: voidView(mreal TetX, mreal TetZ, mreal TetY=0)
-
C function: voidmgl_view(HMGL gr, mreal TetX, mreal TetZ, mreal TetY)
-
Rotates a further plotting relative to each axis {x, z, y} consecutively on angles TetX, TetZ, TetY. Rotation is done independently on rotate. Attention! this settings can not be overwritten by DefaultPlotParam(). Use Zoom(0,0,1,1) to return default view.
-
The function changes the scale of graphics that correspond to zoom in/out of the picture. After function call the current plot will be cleared and further the picture will contain plotting from its part [x1,x2]*[y1,y2]. Here picture coordinates x1, x2, y1, y2 changes from 0 to 1. Attention! this settings can not be overwritten by any other functions, including DefaultPlotParam(). Use Zoom(0,0,1,1) to return default view.
-
Functions in this group save or give access to produced picture. So, usually they should be called after plotting is done.
-
-
-
MGL command: setsizew h
-
Method on mglGraph: voidSetSize(int width, int height, bool clear=true)
-
C function: voidmgl_set_size(HMGL gr, int width, int height)
-
C function: voidmgl_scale_size(HMGL gr, int width, int height)
-
Sets size of picture in pixels. This function should be called before any other plotting because it completely remove picture contents if clear=true. Function just clear pixels and scale all primitives if clear=false.
-
-
-
-
MGL command: setsizesclfactor
-
Method on mglGraph: voidSetSizeScl(double factor)
-
C function: voidmgl_set_size_scl(HMGL gr, double factor)
-
Set factor for width and height in all further calls of setsize. This command is obsolete since v.2.4.2.
-
-
-
-
MGL command: quality[val=2]
-
Method on mglGraph: voidSetQuality(int val=MGL_DRAW_NORM)
-
C function: voidmgl_set_quality(HMGL gr, int val)
-
Sets quality of the plot depending on value val: MGL_DRAW_WIRE=0 – no face drawing (fastest), MGL_DRAW_FAST=1 – no color interpolation (fast), MGL_DRAW_NORM=2 – high quality (normal), MGL_DRAW_HIGH=3 – high quality with 3d primitives (arrows and marks); MGL_DRAW_LMEM=0x4 – direct bitmap drawing (low memory usage); MGL_DRAW_DOTS=0x8 – for dots drawing instead of primitives (extremely fast).
-
-
-
-
Method on mglGraph: intGetQuality()
-
C function: intmgl_get_quality(HMGL gr)
-
Gets quality of the plot: MGL_DRAW_WIRE=0 – no face drawing (fastest), MGL_DRAW_FAST=1 – no color interpolation (fast), MGL_DRAW_NORM=2 – high quality (normal), MGL_DRAW_HIGH=3 – high quality with 3d primitives (arrows and marks); MGL_DRAW_LMEM=0x4 – direct bitmap drawing (low memory usage); MGL_DRAW_DOTS=0x8 – for dots drawing instead of primitives (extremely fast).
-
-
-
-
Method on mglGraph: voidStartGroup(const char *name)
-
C function: voidmgl_start_group(HMGL gr, const char *name)
-
Starts group definition. Groups contain objects and other groups, they are used to select a part of a model to zoom to or to make invisible or to make semitransparent and so on.
-
These functions export current view to a graphic file. The filename fname should have appropriate extension. Parameter descr gives the short description of the picture. Just now the transparency is supported in PNG, SVG, OBJ and PRC files.
-
-
-
MGL command: write['fname'='']
-
Method on mglGraph: voidWriteFrame(const char *fname="", const char *descr="")
-
C function: voidmgl_write_frame(HMGL gr, const char *fname, const char *descr)
-
Exports current frame to a file fname which type is determined by the extension. Parameter descr adds description to file (can be ""). If fname="" then the file ‘frame####.jpg’ is used, where ‘####’ is current frame id and name ‘frame’ is defined by plotid class property.
-
-
-
-
MGL command: bboxx1 y1 [x2=-1 y2=-1]
-
Method on mglGraph: voidSetBBox(int x1=0, int y1=0, int x2=-1, int y2=-1)
-
C function: voidmgl_set_bbox(HMGL gr, int x1, int y1, int x2, int y2)
-
Set boundary box for export graphics into 2D file formats. If x2<0 (y2<0) then original image width (height) will be used. If x1<0 or y1<0 or x1>=x2|Width or y1>=y2|Height then cropping will be disabled.
-
-
-
-
-
-
Method on mglGraph: voidWritePNG(const char *fname, const char *descr="", int compr="", bool alpha=true)
-
C function: voidmgl_write_png(HMGL gr, const char *fname, const char *descr)
-
C function: voidmgl_write_png_solid(HMGL gr, const char *fname, const char *descr)
-
Exports current frame to PNG file. Parameter fname specifies the file name, descr adds description to file, alpha gives the transparency type. By default there are no description added and semitransparent image used. This function does nothing if HAVE_PNG isn’t defined during compilation of MathGL library.
-
-
-
-
Method on mglGraph: voidWriteJPEG(const char *fname, const char *descr="")
-
C function: voidmgl_write_jpg(HMGL gr, const char *fname, const char *descr)
-
Exports current frame to JPEG file. Parameter fname specifies the file name, descr adds description to file. By default there is no description added. This function does nothing if HAVE_JPEG isn’t defined during compilation of MathGL library.
-
-
-
-
Method on mglGraph: voidWriteGIF(const char *fname, const char *descr="")
-
C function: voidmgl_write_gif(HMGL gr, const char *fname, const char *descr)
-
Exports current frame to GIF file. Parameter fname specifies the file name, descr adds description to file. By default there is no description added. This function does nothing if HAVE_GIF isn’t defined during compilation of MathGL library.
-
-
-
-
Method on mglGraph: voidWriteBMP(const char *fname, const char *descr="")
-
C function: voidmgl_write_bmp(HMGL gr, const char *fname, const char *descr)
-
Exports current frame to BMP file. Parameter fname specifies the file name, descr adds description to file. There is no compression used.
-
-
-
-
Method on mglGraph: voidWriteTGA(const char *fname, const char *descr="")
-
C function: voidmgl_write_tga(HMGL gr, const char *fname, const char *descr)
-
Exports current frame to TGA file. Parameter fname specifies the file name, descr adds description to file. There is no compression used.
-
-
-
-
Method on mglGraph: voidWriteEPS(const char *fname, const char *descr="")
-
C function: voidmgl_write_eps(HMGL gr, const char *fname, const char *descr)
-
Exports current frame to EPS file using vector representation. So it is not recommended for the export of large data plot. It is better to use bitmap format (for example PNG or JPEG). However, program has no internal limitations for size of output file. Parameter fname specifies the file name, descr adds description to file. By default there is no description added. If file name is terminated by ‘z’ (for example, ‘fname.eps.gz’) then file will be compressed in gzip format. Note, that EPS format don’t support color interpolation, and the resulting plot will look as you use quality=1 for plotting.
-
-
-
-
Method on mglGraph: voidWriteBPS(const char *fname, const char *descr="")
-
C function: voidmgl_write_eps(HMGL gr, const char *fname, const char *descr)
-
Exports current frame to EPS file using bitmap representation. Parameter fname specifies the file name, descr adds description to file. By default there is no description added. If file name is terminated by ‘z’ (for example, ‘fname.eps.gz’) then file will be compressed in gzip format.
-
-
-
-
Method on mglGraph: voidWriteSVG(const char *fname, const char *descr="")
-
C function: voidmgl_write_svg(HMGL gr, const char *fname, const char *descr)
-
Exports current frame to SVG (Scalable Vector Graphics) file using vector representation. In difference of EPS format, SVG format support transparency that allows to correctly draw semitransparent plot (like surfa, surf3a or cloud). Note, the output file may be too large for graphic of large data array (especially for surfaces). It is better to use bitmap format (for example PNG or JPEG). However, program has no internal limitations for size of output file. Parameter fname specifies the file name, descr adds description to file (default is file name). If file name is terminated by ‘z’ (for example, ‘fname.svgz’) then file will be compressed in gzip format. Note, that SVG format don’t support color interpolation, and the resulting plot will look as you use quality=1 for plotting.
-
-
-
-
Method on mglGraph: voidWriteTEX(const char *fname, const char *descr="")
-
C function: voidmgl_write_tex(HMGL gr, const char *fname, const char *descr)
-
Exports current frame to LaTeX (package Tikz/PGF) file using vector representation. Note, the output file may be too large for graphic of large data array (especially for surfaces). It is better to use bitmap format (for example PNG or JPEG). However, program has no internal limitations for size of output file. Parameter fname specifies the file name, descr adds description to file (default is file name). Note, there is no text scaling now (for example, in subplots), what may produce miss-aligned labels.
-
C function: voidmgl_write_prc(HMGL gr, const char *fname, const char *descr, int make_pdf)
-
Exports current frame to PRC file using vector representation (see http://en.wikipedia.org/wiki/PRC_%28file_format%29). Note, the output file may be too large for graphic of large data array (especially for surfaces). It is better to use bitmap format (for example PNG or JPEG). However, program has no internal limitations for size of output file. Parameter fname specifies the file name, descr adds description to file (default is file name). If parameter make_pdf=true and PDF was enabled at MathGL configure then corresponding PDF file with 3D image will be created.
-
-
-
-
Method on mglGraph: voidWriteOBJ(const char *fname, const char *descr="")
-
C function: voidmgl_write_obj(HMGL gr, const char *fname, const char *descr)
-
Exports current frame to OBJ/MTL file using vector representation (see OBJ format for details). Note, the output file may be too large for graphic of large data array (especially for surfaces). It is better to use bitmap format (for example PNG or JPEG). However, program has no internal limitations for size of output file. Parameter fname specifies the file name, descr adds description to file (default is file name).
-
-
-
-
Method on mglGraph: voidWriteXYZ(const char *fname, const char *descr="")
-
C function: voidmgl_write_xyz(HMGL gr, const char *fname, const char *descr)
-
Exports current frame to XYZ/XYZL/XYZF files using vector representation (see XYZ format for details). Note, the output file may be too large for graphic of large data array (especially for surfaces). It is better to use bitmap format (for example PNG or JPEG). However, program has no internal limitations for size of output file. Parameter fname specifies the file name, descr adds description to file (default is file name).
-
-
-
-
Method on mglGraph: voidWriteSTL(const char *fname, const char *descr="")
-
C function: voidmgl_write_stl(HMGL gr, const char *fname, const char *descr)
-
Exports current frame to STL file using vector representation (see STL format for details). Note, the output file may be too large for graphic of large data array (especially for surfaces). It is better to use bitmap format (for example PNG or JPEG). However, program has no internal limitations for size of output file. Parameter fname specifies the file name, descr adds description to file (default is file name.
-
Exports current frame to OFF file using vector representation (see OFF format for details). Note, the output file may be too large for graphic of large data array (especially for surfaces). It is better to use bitmap format (for example PNG or JPEG). However, program has no internal limitations for size of output file. Parameter fname specifies the file name, descr adds description to file (default is file name).
-
-
-
-
-
-
-
Method on mglGraph: voidShowImage(const char *viewer, bool nowait=false)
-
C function: voidmgl_show_image(const char *viewer, int nowait)
-
Displays the current picture using external program viewer for viewing. The function save the picture to temporary file and call viewer to display it. If nowait=true then the function return immediately (it will not wait while window will be closed).
-
-
-
-
-
Method on mglGraph: voidWriteJSON(const char *fname, const char *descr="")
-
C function: voidmgl_write_json(HMGL gr, const char *fname, const char *descr)
-
Exports current frame to textual file using JSON format. Later this file can be used for faster loading and viewing by JavaScript script. Parameter fname specifies the file name, descr adds description to file.
-
-
-
-
Method on mglGraph: voidExportMGLD(const char *fname, const char *descr="")
-
C function: voidmgl_export_mgld(HMGL gr, const char *fname, const char *descr)
-
Exports points and primitives in file using MGLD format. Later this file can be used for faster loading and viewing by mglview utility. Parameter fname specifies the file name, descr adds description to file (default is file name).
-
-
-
-
Method on mglGraph: voidImportMGLD(const char *fname, bool add=false)
-
C function: voidmgl_import_mgld(HMGL gr, const char *fname, int add)
-
Imports points and primitives in file using MGLD format. Later this file can be used for faster loading and viewing by mglview utility. Parameter fname specifies the file name, add sets to append or replace primitives to existed ones.
-
These functions provide ability to create several pictures simultaneously. For most of cases it is useless but for widget classes (see Widget classes) they can provide a way to show animation. Also you can write several frames into animated GIF file.
-
-
-
Method on mglGraph: voidNewFrame()
-
C function: voidmgl_new_frame(HMGL gr)
-
Creates new frame. Function returns current frame id. This is not thread safe function in OpenGL mode! Use direct list creation in multi-threading drawing. The function EndFrame()must be call after the finishing of the frame drawing for each call of this function.
-
-
-
-
Method on mglGraph: voidEndFrame()
-
C function: voidmgl_end_frame(HMGL gr)
-
Finishes the frame drawing.
-
-
-
-
Method on mglGraph: intGetNumFrame()
-
C function: intmgl_get_num_frame(HMGL gr)
-
Gets the number of created frames.
-
-
-
-
Method on mglGraph: voidSetFrame(int i)
-
C function: voidmgl_set_frame(HMGL gr, int i)
-
Finishes the frame drawing and sets drawing data to frame i, which should be in range [0, GetNumFrame()-1]. This function is similar to EndFrame() but don’t add frame to the GIF image.
-
-
-
-
Method on mglGraph: voidGetFrame(int i)
-
C function: voidmgl_get_frame(HMGL gr, int i)
-
Replaces drawing data by one from frame i. Function work if MGL_VECT_FRAME is set on (by default).
-
-
-
-
Method on mglGraph: voidShowFrame(int i)
-
C function: voidmgl_show_frame(HMGL gr, int i)
-
Appends drawing data from frame i to current one. Function work if MGL_VECT_FRAME is set on (by default).
-
-
-
-
Method on mglGraph: voidDelFrame(int i)
-
C function: voidmgl_del_frame(HMGL gr, int i)
-
Deletes drawing data for frame i and shift all later frame indexes. Function work if MGL_VECT_FRAME is set on (by default). Do nothing in OpenGL mode.
-
-
-
-
Method on mglGraph: voidResetFrames()
-
C function: voidmgl_reset_frames(HMGL gr)
-
Reset frames counter (start it from zero).
-
-
-
-
Method on mglGraph: voidClearFrame(int i)
-
C function: voidmgl_clear_frame(HMGL gr, int i)
-
Clear list of primitives for current drawing.
-
-
-
-
Method on mglGraph: voidStartGIF(const char *fname, int ms=100)
-
C function: voidmgl_start_gif(HMGL gr, const char *fname, int ms)
-
Start writing frames into animated GIF file fname. Parameter ms set the delay between frames in milliseconds. You should not change the picture size during writing the cinema. Use CloseGIF() to finalize writing. Note, that this function is disabled in OpenGL mode.
-
-
-
-
Method on mglGraph: voidCloseGIF()
-
C function: voidmgl_close_gif(HMGL gr)
-
Finish writing animated GIF and close connected pointers.
-
These functions return the created picture (bitmap), its width and height. You may display it by yourself in any graphical library (see also, Widget classes) or save in file (see also, Export to file).
-
-
-
Method on mglGraph: const unsigned char *GetRGB()
-
Method on mglGraph: voidGetRGB(char *buf, int size)
-
Method on mglGraph: voidGetBGRN(char *buf, int size)
-
C function: const unsigned char *mgl_get_rgb(HMGL gr)
-
Gets RGB bitmap of the current state of the image. Format of each element of bits is: {red, green, blue}. Number of elements is Width*Height. Position of element {i,j} is [3*i + 3*Width*j] (or is [4*i + 4*Width*j] for GetBGRN()). You have to provide the proper size of the buffer, buf, i.e. the code for Python should look like
-
Method on mglGraph: const unsigned char *GetRGBA()
-
Method on mglGraph: voidGetRGBA(char *buf, int size)
-
C function: const unsigned char *mgl_get_rgba(HMGL gr)
-
Gets RGBA bitmap of the current state of the image. Format of each element of bits is: {red, green, blue, alpha}. Number of elements is Width*Height. Position of element {i,j} is [4*i + 4*Width*j].
-
-
-
-
Method on mglGraph: intGetWidth()
-
Method on mglGraph: intGetHeight()
-
C function: intmgl_get_width(HMGL gr)
-
C function: intmgl_get_height(HMGL gr)
-
Gets width and height of the image.
-
-
-
-
-
Method on mglGraph: mglPointCalcXYZ(int xs, int ys)
-
C function: voidmgl_calc_xyz(HMGL gr, int xs, int ys, mreal *x, mreal *y, mreal *z)
-
Calculate 3D coordinate {x,y,z} for screen point {xs,ys}. At this moment it ignore perspective and transformation formulas (curvilinear coordinates). The calculation are done for the last used InPlot (see Subplots and rotation).
-
-
-
-
Method on mglGraph: mglPointCalcScr(mglPoint p)
-
C function: voidmgl_calc_scr(HMGL gr, mreal x, mreal y, mreal z, int *xs, int *ys)
-
Calculate screen point {xs,ys} for 3D coordinate {x,y,z}. The calculation are done for the last used InPlot (see Subplots and rotation).
-
-
-
-
Method on mglGraph: voidSetObjId(int id)
-
C function: voidmgl_set_obj_id(HMGL gr, int id)
-
Set the numeric id for object or subplot/inplot.
-
-
-
-
Method on mglGraph: intGetObjId(int xs, int ys)
-
C function: intmgl_get_obj_id(HMGL gr, int xs, int ys)
-
Get the numeric id for most upper object at pixel {xs, ys} of the picture.
-
-
-
-
Method on mglGraph: intGetSplId(int xs, int ys)
-
C function: intmgl_get_spl_id(HMGL gr, int xs, int ys)
-
Get the numeric id for most subplot/inplot at pixel {xs, ys} of the picture.
-
-
-
-
Method on mglGraph: voidHighlight(int id)
-
C function: voidmgl_highlight(HMGL gr, int id)
-
Highlight the object with given id.
-
-
-
-
Method on mglGraph: longIsActive(int xs, int ys, int d=1)
-
C function: longmgl_is_active(HMGL gr, int xs, int ys, int d)
-
Checks if point {xs, ys} is close to one of active point (i.e. mglBase::Act) with accuracy d and return its index or -1 if not found. Active points are special points which characterize primitives (like edges and so on). This function for advanced users only.
-
-
-
-
Method on mglGraph: longSetDrawReg(int nx=1, int ny=1, int m=0)
-
C function: longmgl_set_draw_reg(HMGL gr, int nx, int ny, int m)
-
Limits drawing region by rectangular area of m-th cell of matrix with sizes nx*ny (like in subplot). This function can be used to update only small region of the image for purposes of higher speed. This function for advanced users only.
-
Many of things MathGL do in parallel by default (if MathGL was built with pthread). However, there is function which set the number of threads to be used.
-
-
-
C function: intmgl_set_num_thr(int n)
-
Set the number of threads to be used by MathGL. If n<1 then the number of threads is set as maximal number of processors (cores). If n=1 then single thread will be used (this is default if pthread was disabled).
-
-
-
Another option is combining bitmap image (taking into account Z-ordering) from different instances of mglGraph. This method is most appropriate for computer clusters when the data size is so large that it exceed the memory of single computer node.
-
-
-
Method on mglGraph: intCombine(const mglGraph *g)
-
C function: intmgl_combine_gr(HMGL gr, HMGL g)
-
Combine drawing from instance g with gr (or with this) taking into account Z-ordering of pixels. The width and height of both instances must be the same.
-
-
-
-
Method on mglGraph: intMPI_Send(int id)
-
C function: intmgl_mpi_send(HMGL gr, int id)
-
Send graphical information from node id using MPI. The width and height in both nodes must be the same.
-
-
-
-
Method on mglGraph: intMPI_Recv(int id)
-
C function: intmgl_mpi_send(HMGL gr, int id)
-
Receive graphical information from node id using MPI. The width and height in both nodes must be the same.
-
Method on mglGraph: voidClf(mreal r, mreal g, mreal b)
-
C function: voidmgl_clf(HMGL gr)
-
C function: voidmgl_clf_str(HMGL gr, const char * col)
-
C function: voidmgl_clf_chr(HMGL gr, char col)
-
C function: voidmgl_clf_rgb(HMGL gr, mreal r, mreal g, mreal b)
-
Clear the picture and fill background by specified color.
-
-
-
-
MGL command: rasterize
-
Method on mglGraph: voidRasterize()
-
C function: voidmgl_rasterize(HMGL gr)
-
Force drawing the plot and use it as background. After it, function clear the list of primitives, like clf. This function is useful if you want save part of plot as bitmap one (for example, large surfaces, isosurfaces or vector fields) and keep some parts as vector one (like annotation, curves, axis and so on).
-
-
-
-
MGL command: background'fname' [alpha=1]
-
Method on mglGraph: voidLoadBackground(const char * fname, double alpha=1)
-
C function: voidmgl_load_background(HMGL gr, const char * fname, double alpha)
-
Load PNG or JPEG file fname as background for the plot. Parameter alpha manually set transparency of the background.
-
These functions draw some simple objects like line, point, sphere, drop, cone and so on. See Using primitives, for sample code and picture.
-
-
-
MGL command: ballx y ['col'='r.']
-
MGL command: ballx y z ['col'='r.']
-
Method on mglGraph: voidBall(mglPoint p, char col='r')
-
Method on mglGraph: voidMark(mglPoint p, const char *mark)
-
C function: voidmgl_mark(HMGL gr, mreal x, mreal y, mreal z, const char *mark)
-
Draws a mark (point ‘.’ by default) at position p={x, y, z} with color col.
-
-
-
-
MGL command: errboxx y ex ey ['stl'='']
-
MGL command: errboxx y z ex ey ez ['stl'='']
-
Method on mglGraph: voidError(mglPoint p, mglPoint e, char *stl="")
-
C function: voidmgl_error_box(HMGL gr, mreal x, mreal y, mreal z, mreal ex, mreal ey, mreal ez, char *stl)
-
Draws a 3d error box at position p={x, y, z} with sizes e={ex, ey, ez} and style stl. Use NAN for component of e to reduce number of drawn elements.
-
-
-
-
MGL command: linex1 y1 x2 y2 ['stl'='']
-
MGL command: linex1 y1 z1 x2 y2 z2 ['stl'='']
-
Method on mglGraph: voidLine(mglPoint p1, mglPoint p2, char *stl="B", int num=2)
-
C function: voidmgl_line(HMGL gr, mreal x1, mreal y1, mreal z1, mreal x2, mreal y2, mreal z2, char *stl, int num)
-
Draws a geodesic line (straight line in Cartesian coordinates) from point p1 to p2 using line style stl. Parameter num define the “quality” of the line. If num=2 then the straight line will be drawn in all coordinate system (independently on transformation formulas (see Curved coordinates). Contrary, for large values (for example, =100) the geodesic line will be drawn in corresponding coordinate system (straight line in Cartesian coordinates, circle in polar coordinates and so on). Line will be drawn even if it lies out of bounding box.
-
Draws Bezier-like curve from point p1 to p2 using line style stl. At this tangent is codirected with d1, d2 and proportional to its amplitude. Parameter num define the “quality” of the curve. If num=2 then the straight line will be drawn in all coordinate system (independently on transformation formulas, see Curved coordinates). Contrary, for large values (for example, =100) the spline like Bezier curve will be drawn in corresponding coordinate system. Curve will be drawn even if it lies out of bounding box.
-
Draws the solid quadrangle (face) with vertexes p1, p2, p3, p4 and with color(s) stl. At this colors can be the same for all vertexes or different if all 4 colors are specified for each vertex. Face will be drawn even if it lies out of bounding box.
-
-
-
-
MGL command: rectx1 y1 x2 y2 ['stl'='']
-
MGL command: rectx1 y1 z1 x2 y2 z2 ['stl'='']
-
Draws the solid rectangle (face) with vertexes {x1, y1, z1} and {x2, y2, z2} with color stl. At this colors can be the same for all vertexes or separately if all 4 colors are specified for each vertex. Face will be drawn even if it lies out of bounding box.
-
Draws the solid rectangle (face) perpendicular to [x,y,z]-axis correspondingly at position {x0, y0, z0} with color stl and with widths wx, wy, wz along corresponding directions. At this colors can be the same for all vertexes or separately if all 4 colors are specified for each vertex. Parameters d1!=0, d2!=0 set additional shift of the last vertex (i.e. to draw quadrangle). Face will be drawn even if it lies out of bounding box.
-
-
-
-
MGL command: spherex0 y0 r ['col'='r']
-
MGL command: spherex0 y0 z0 r ['col'='r']
-
Method on mglGraph: voidSphere(mglPoint p, mreal r, const char *stl="r")
Draw the drop with radius r at point p elongated in direction d and with color col. Parameter shift set the degree of drop oblongness: ‘0’ is sphere, ‘1’ is maximally oblongness drop. Parameter ap set relative width of the drop (this is analogue of “ellipticity” for the sphere).
-
Draw tube (or truncated cone if edge=false) between points p1, p2 with radius at the edges r1, r2. If r2<0 then it is supposed that r2=r1. The cone color is defined by string stl. Parameter stl can contain:
-
-
‘@’ for drawing edges;
-
‘#’ for wired cones;
-
‘t’ for drawing tubes/cylinder instead of cones/prisms;
-
‘4’, ‘6’, ‘8’ for drawing square, hex- or octo-prism instead of cones.
-
-
-
-
-
MGL command: circlex0 y0 r ['col'='r']
-
MGL command: circlex0 y0 z0 r ['col'='r']
-
Method on mglGraph: voidCircle(mglPoint p, mreal r, const char *stl="r")
-
Draw the circle with radius r and center at point p={x0, y0, z0}. Parameter col may contain
-
-
colors for filling and boundary (second one if style ‘@’ is used, black color is used by default);
-
‘#’ for wire figure (boundary only);
-
‘@’ for filling and boundary.
-
-
-
-
-
MGL command: ellipsex1 y1 x2 y2 r ['col'='r']
-
MGL command: ellipsex1 y1 z1 x2 y2 z2 r ['col'='r']
Draw the rhombus with width r and edge points p1, p2. Parameter col may contain
-
-
colors for filling and boundary (second one if style ‘@’ is used, black color is used by default);
-
‘#’ for wire figure (boundary only);
-
‘@’ for filling and boundary.
-
-
-
-
-
MGL command: arcx0 y0 x1 y1 a ['col'='r']
-
MGL command: arcx0 y0 z0 x1 y1 a ['col'='r']
-
MGL command: arcx0 y0 z0 xa ya za x1 y1 z1 a ['col'='r']
-
Method on mglGraph: voidArc(mglPoint p0, mglPoint p1, mreal a, const char *col="r")
-
Method on mglGraph: voidArc(mglPoint p0, mglPoint pa, mglPoint p1, mreal a, const char *col="r")
-
C function: voidmgl_arc(HMGL gr, mreal x0, mreal y0, mreal x1, mreal y1, mreal a, const char *col)
-
C function: voidmgl_arc_ext(HMGL gr, mreal x0, mreal y0, mreal z0, mreal xa, mreal ya, mreal za, mreal x1, mreal y1, mreal z1, mreal a, const char *col)
-
Draw the arc around axis pa (default is z-axis pa={0,0,1}) with center at p0 and starting from point p1. Parameter a set the angle of arc in degree. Parameter col may contain color of the arc and arrow style for arc edges.
-
-
-
-
MGL command: polygonx0 y0 x1 y1 num ['col'='r']
-
MGL command: polygonx0 y0 z0 x1 y1 z1 num ['col'='r']
-
Method on mglGraph: voidPolygon(mglPoint p0, mglPoint p1, int num, const char *col="r")
Draw bitmap (logo) along whole axis range, which can be changed by Command options. Bitmap can be loaded from file or specified as RGBA values for pixels. Parameter smooth set to draw bitmap without or with color interpolation.
-
C function: voidmgl_symbol(HMGL gr, mreal x, mreal y, mreal z, char id, const char *fnt, mreal size)
-
Draws user-defined symbol with name id at position p with style specifying by fnt. The size of font is set by size parameter (default is -1). The string fnt may contain color specification ended by ‘:’ symbol; styles ‘a’, ‘A’ to draw at absolute position {x, y} (supposed to be in range [0,1]) of picture (for ‘A’) or subplot/inplot (for ‘a’); and style ‘w’ to draw wired symbol.
-
-
-
-
MGL command: symbolx y dx dy 'id' ['fnt'=':L' size=-1]
-
MGL command: symbolx y z dx dy dz 'id' ['fnt'=':L' size=-1]
These functions draw the text. There are functions for drawing text in arbitrary place, in arbitrary direction and along arbitrary curve. MathGL can use arbitrary font-faces and parse many TeX commands (for more details see Font styles). All these functions have 2 variant: for printing 8-bit text (char *) and for printing Unicode text (wchar_t *). In first case the conversion into the current locale is used. So sometimes you need to specify it by setlocale() function. The size argument control the size of text: if positive it give the value, if negative it give the value relative to SetFontSize(). The font type (STIX, arial, courier, times and so on) can be selected by function LoadFont(). See Font settings.
-
-
The font parameters are described by string. This string may set the text color ‘wkrgbcymhRGBCYMHW’ (see Color styles). Starting from MathGL v.2.3, you can set color gradient for text (see Color scheme). Also, after delimiter symbol ‘:’, it can contain characters of font type (‘rbiwou’) and/or align (‘LRCTV’) specification. The font types are: ‘r’ – roman (or regular) font, ‘i’ – italic style, ‘b’ – bold style, ‘w’ – wired style, ‘o’ – over-lined text, ‘u’ – underlined text. By default roman font is used. The align types are: ‘L’ – align left (default), ‘C’ – align center, ‘R’ – align right, ‘T’ – align under, ‘V’ – align center vertical. For example, string ‘b:iC’ correspond to italic font style for centered text which printed by blue color.
-
-
If string contains symbols ‘aA’ then text is printed at absolute position {x, y} (supposed to be in range [0,1]) of picture (for ‘A’) or subplot/inplot (for ‘a’). If string contains symbol ‘@’ then box around text is drawn.
-
Draws the string text at position p along direction d with specified size. Parameter fnt set text style and text position: under (‘T’) or above (‘t’) the line.
-
-
-
-
MGL command: fgetsx y 'fname' [n=0 'fnt'='' size=-1.4]
-
MGL command: fgetsx y z 'fname' [n=0 'fnt'='' size=-1.4]
-
Draws unrotated n-th line of file fname at position {x,y,z} with specified size. By default parameters from font command are used.
-
C function: voidmgl_text_y(HMGL gr, HCDT y, const char *text, const char *fnt, const char *opt)
-
C function: voidmgl_textw_y(HMGL gr, HCDT y, const wchar_t *text, const char *fnt, const char *opt)
-
C function: voidmgl_text_xy(HCDT x, HCDT y, const char *text, const char *fnt, const char *opt)
-
C function: voidmgl_textw_xy(HCDT x, HCDT y, const wchar_t *text, const char *fnt, const char *opt)
-
C function: voidmgl_text_xyz(HCDT x, HCDT y, HCDT z, const char *text, const char *fnt, const char *opt)
-
C function: voidmgl_textw_xyz(HCDT x, HCDT y, HCDT z, const wchar_t *text, const char *fnt, const char *opt)
-
The function draws text along the curve between points {x[i], y[i], z[i]} by font style fnt. The string fnt may contain symbols ‘t’ for printing the text under the curve (default), or ‘T’ for printing the text under the curve. The sizes of 1st dimension must be equal for all arrays x.nx=y.nx=z.nx. If array x is not specified then its an automatic array is used with values equidistantly distributed in x-axis range (see Ranges (bounding box)). If array z is not specified then z[i] equal to minimal z-axis value is used. String opt contain command options (see Command options).
-
These functions draw the “things for measuring”, like axis with ticks, colorbar with ticks, grid along axis, bounding box and labels for axis. For more information see Axis settings.
-
‘AKDTVISO’ for drawing arrow at the end of axis;
-
‘a’ for forced adjusting of axis ticks;
-
‘:’ for drawing lines through point (0,0,0);
-
‘f’ for printing ticks labels in fixed format;
-
‘E’ for using ‘E’ instead of ‘e’ in ticks labels;
-
‘F’ for printing ticks labels in LaTeX format;
-
‘+’ for printing ‘+’ for positive ticks;
-
‘-’ for printing usual ‘-’ in ticks labels;
-
‘0123456789’ for precision at printing ticks labels.
-
-
Styles of ticks and axis can be overrided by using stl string. Option value set the manual rotation angle for the ticks. See Axis and ticks, for sample code and picture.
-
-
-
-
MGL command: colorbar['sch'='']
-
Method on mglGraph: voidColorbar(const char *sch="")
-
C function: voidmgl_colorbar(HMGL gr, const char *sch)
Method on mglGraph: voidColorbar(const mglDataA &v, const char *sch="")
-
C function: voidmgl_colorbar_val(HMGL gr, HCDT v, const char *sch)
-
The same as previous but with sharp colors sch (current palette if sch="") for values v. See contd sample, for sample code and picture.
-
-
-
-
MGL command: colorbar'sch' x y [w=1 h=1]
-
Method on mglGraph: voidColorbar(const char *sch, mreal x, mreal y, mreal w=1, mreal h=1)
-
C function: voidmgl_colorbar_ext(HMGL gr, const char *sch, mreal x, mreal y, mreal w, mreal h)
-
The same as first one but at arbitrary position of subplot {x, y} (supposed to be in range [0,1]). Parameters w, h set the relative width and height of the colorbar.
-
-
-
-
MGL command: colorbarvdat 'sch' x y [w=1 h=1]
-
Method on mglGraph: voidColorbar(const mglDataA &v, const char *sch, mreal x, mreal y, mreal w=1, mreal h=1)
-
C function: voidmgl_colorbar_val_ext(HMGL gr, HCDT v, const char *sch, mreal x, mreal y, mreal w, mreal h)
-
The same as previous but with sharp colors sch (current palette if sch="") for values v. See contd sample, for sample code and picture.
-
Draws grid lines perpendicular to direction determined by string parameter dir. If dir contain ‘!’ then grid lines will be drawn at coordinates of subticks also. The step of grid lines is the same as tick step for axis. The style of lines is determined by pen parameter (default value is dark blue solid line ‘B-’).
-
-
-
-
MGL command: box['stl'='k' ticks=on]
-
Method on mglGraph: voidBox(const char *col="", bool ticks=true)
-
C function: voidmgl_box(HMGL gr)
-
C function: voidmgl_box_str(HMGL gr, const char *col, int ticks)
-
Draws bounding box outside the plotting volume with color col. If col contain ‘@’ then filled faces are drawn. At this first color is used for faces (default is light yellow), last one for edges. See Bounding box, for sample code and picture.
-
Prints the label text for axis dir=‘x’,‘y’,‘z’,‘t’,‘c’, where ‘t’ is “ternary” axis t=1-x-y; ‘c’ is color axis (should be called after colorbar). The position of label is determined by pos parameter. If pos=0 then label is printed at the center of axis. If pos>0 then label is printed at the maximum of axis. If pos<0 then label is printed at the minimum of axis. Option value set additional shifting of the label. See Text printing.
-
These functions draw legend to the graph (useful for 1D plotting). Legend entry is a pair of strings: one for style of the line, another one with description text (with included TeX parsing). The arrays of strings may be used directly or by accumulating first to the internal arrays (by function addlegend) and further plotting it. The position of the legend can be selected automatic or manually (even out of bounding box). Parameters fnt and size specify the font style and size (see Font settings). Option value set the relative width of the line sample and the text indent. If line style string for entry is empty then the corresponding text is printed without indent. Parameter fnt may contain:
-
-
font style for legend text;
-
‘A’ for positioning in absolute coordinates;
-
‘^’ for positioning outside of specified point;
-
‘#’ for drawing box around legend;
-
‘-’ for arranging legend entries horizontally;
-
colors for face (1st one), for border (2nd one) and for text (last one). If less than 3 colors are specified then the color for border is black (for 2 and less colors), and the color for face is white (for 1 or none colors).
-
C function: voidmgl_legend(HMGL gr, int pos, const char *fnt, const char *opt)
-
Draws legend of accumulated legend entries by font fnt with size. Parameter pos sets the position of the legend: ‘0’ is bottom left corner, ‘1’ is bottom right corner, ‘2’ is top left corner, ‘3’ is top right corner (is default). Option value set the space between line samples and text (default is 0.1).
-
-
-
-
MGL command: legendx y ['fnt'='#']
-
Method on mglGraph: voidLegend(mreal x, mreal y, const char *fnt="#", const char *opt="")
-
C function: voidmgl_legend_pos(HMGL gr, mreal x, mreal y, const char *fnt, const char *opt)
-
Draws legend of accumulated legend entries by font fnt with size. Position of legend is determined by parameter x, y which supposed to be normalized to interval [0,1]. Option value set the space between line samples and text (default is 0.1).
-
-
-
-
MGL command: addlegend'text' 'stl'
-
Method on mglGraph: voidAddLegend(const char *text, const char *style)
-
Method on mglGraph: voidAddLegend(const wchar_t *text, const char *style)
-
C function: voidmgl_add_legend(HMGL gr, const char *text, const char *style)
-
C function: voidmgl_add_legendw(HMGL gr, const wchar_t *text, const char *style)
-
Adds string text to internal legend accumulator. The style of described line and mark is specified in string style (see Line styles).
-
-
-
-
MGL command: clearlegend
-
Method on mglGraph: voidClearLegend()
-
C function: voidmgl_clear_legend(HMGL gr)
-
Clears saved legend strings.
-
-
-
-
MGL command: legendmarksval
-
Method on mglGraph: voidSetLegendMarks(int num)
-
C function: voidmgl_set_legend_marks(HMGL gr, int num)
-
Set the number of marks in the legend. By default 1 mark is used.
-
These functions perform plotting of 1D data. 1D means that data depended from only 1 parameter like parametric curve {x[i],y[i],z[i]}, i=1...n. By default (if absent) values of x[i] are equidistantly distributed in axis range, and z[i] equal to minimal z-axis value. The plots are drawn for each row if one of the data is the matrix. By any case the sizes of 1st dimension must be equal for all arrays x.nx=y.nx=z.nx.
-
-
String pen specifies the color and style of line and marks (see Line styles). By default (pen="") solid line with color from palette is used (see Palette and colors). Symbol ‘!’ set to use new color from palette for each point (not for each curve, as default). String opt contain command options (see Command options).
-
C function: voidmgl_plot(HMGL gr, HCDT y, const char *pen, const char *opt)
-
C function: voidmgl_plot_xy(HMGL gr, HCDT x, HCDT y, const char *pen, const char *opt)
-
C function: voidmgl_plot_xyz(HMGL gr, HCDT x, HCDT y, HCDT z, const char *pen, const char *opt)
-
These functions draw continuous lines between points {x[i], y[i], z[i]}. If pen contain ‘a’ then segments between points outside of axis range are drawn too. If pen contain ‘~’ then number of segments is reduce for quasi-straight curves. See also area, step, stem, tube, mark, error, belt, tens, tape, meshnum. See plot sample, for sample code and picture.
-
C function: voidmgl_radar(HMGL gr, HCDT a, const char *pen, const char *opt)
-
This functions draws radar chart which is continuous lines between points located on an radial lines (like plot in Polar coordinates). Option value set the additional shift of data (i.e. the data a+value is used instead of a). If value<0 then r=max(0, -min(value). If pen containt ‘#’ symbol then "grid" (radial lines and circle for r) is drawn. If pen contain ‘a’ then segments between points outside of axis range are drawn too. See also plot, meshnum. See radar sample, for sample code and picture.
-
C function: voidmgl_step(HMGL gr, HCDT y, const char *pen, const char *opt)
-
C function: voidmgl_step_xy(HMGL gr, HCDT x, HCDT y, const char *pen, const char *opt)
-
C function: voidmgl_step_xyz(HMGL gr, HCDT x, HCDT y, HCDT z, const char *pen, const char *opt)
-
These functions draw continuous stairs for points to axis plane. If x.nx>y.nx then x set the edges of bars, rather than its central positions. See also plot, stem, tile, boxs, meshnum. See step sample, for sample code and picture.
-
C function: voidmgl_tens(HMGL gr, HCDT y, HCDT c, const char *pen, const char *opt)
-
C function: voidmgl_tens_xy(HMGL gr, HCDT x, HCDT y, HCDT c, const char *pen, const char *opt)
-
C function: voidmgl_tens_xyz(HMGL gr, HCDT x, HCDT y, HCDT z, HCDT c, const char *pen, const char *opt)
-
These functions draw continuous lines between points {x[i], y[i], z[i]} with color defined by the special array c[i] (look like tension plot). String pen specifies the color scheme (see Color scheme) and style and/or width of line (see Line styles). If pen contain ‘a’ then segments between points outside of axis range are drawn too. If pen contain ‘~’ then number of segments is reduce for quasi-straight curves. See also plot, mesh, fall, meshnum. See tens sample, for sample code and picture.
-
C function: voidmgl_tape(HMGL gr, HCDT y, const char *pen, const char *opt)
-
C function: voidmgl_tape_xy(HMGL gr, HCDT x, HCDT y, const char *pen, const char *opt)
-
C function: voidmgl_tape_xyz(HMGL gr, HCDT x, HCDT y, HCDT z, const char *pen, const char *opt)
-
These functions draw tapes of normals for curve between points {x[i], y[i], z[i]}. Initial tape(s) was selected in x-y plane (for ‘x’ in pen) and/or y-z plane (for ‘x’ in pen). The width of tape is proportional to barwidth and can be changed by option value. See also plot, flow, barwidth. See tape sample, for sample code and picture.
-
C function: voidmgl_area(HMGL gr, HCDT y, const char *pen, const char *opt)
-
C function: voidmgl_area_xy(HMGL gr, HCDT x, HCDT y, const char *pen, const char *opt)
-
C function: voidmgl_area_xyz(HMGL gr, HCDT x, HCDT y, HCDT z, const char *pen, const char *opt)
-
These functions draw continuous lines between points and fills it to axis plane. Also you can use gradient filling if number of specified colors is equal to 2*number of curves. If pen contain ‘#’ then wired plot is drawn. If pen contain ‘a’ then segments between points outside of axis range are drawn too. See also plot, bars, stem, region. See area sample, for sample code and picture.
-
These functions fill area between 2 curves. Dimensions of arrays y1 and y2 must be equal. Also you can use gradient filling if number of specified colors is equal to 2*number of curves. If for 2D version pen contain symbol ‘i’ then only area with y1<y<y2 will be filled else the area with y2<y<y1 will be filled too. If pen contain ‘#’ then wired plot is drawn. If pen contain ‘a’ then segments between points outside of axis range are drawn too. See also area, bars, stem. See region sample, for sample code and picture.
-
C function: voidmgl_bars(HMGL gr, HCDT y, const char *pen, const char *opt)
-
C function: voidmgl_bars_xy(HMGL gr, HCDT x, HCDT y, const char *pen, const char *opt)
-
C function: voidmgl_bars_xyz(HMGL gr, HCDT x, HCDT y, HCDT z, const char *pen, const char *opt)
-
These functions draw vertical bars from points to axis plane. Parameter pen can contain:
-
-
‘a’ for drawing lines one above another (like summation);
-
‘f’ for drawing waterfall chart, which show the cumulative effect of sequential positive or negative values;
-
‘F’ for using fixed (minimal) width for all bars;
-
‘<’, ‘^’ or ‘>’ for aligning boxes left, right or centering them at its x-coordinates.
-
-
You can give different colors for positive and negative values if number of specified colors is equal to 2*number of curves. If x.nx>y.nx then x set the edges of bars, rather than its central positions. See also barh, cones, area, stem, chart, barwidth. See bars sample, for sample code and picture.
-
C function: voidmgl_barh_xy(HMGL gr, HCDT y, HCDT v, const char *pen, const char *opt)
-
These functions draw horizontal bars from points to axis plane. Parameter pen can contain:
-
-
‘a’ for drawing lines one above another (like summation);
-
‘f’ for drawing waterfall chart, which show the cumulative effect of sequential positive or negative values;
-
‘F’ for using fixed (minimal) width for all bars;
-
‘<’, ‘^’ or ‘>’ for aligning boxes left, right or centering them at its x-coordinates.
-
-
You can give different colors for positive and negative values if number of specified colors is equal to 2*number of curves. If x.nx>y.nx then x set the edges of bars, rather than its central positions. See also bars, barwidth. See barh sample, for sample code and picture.
-
C function: voidmgl_cones(HMGL gr, HCDT y, const char *pen, const char *opt)
-
C function: voidmgl_cones_xy(HMGL gr, HCDT x, HCDT y, const char *pen, const char *opt)
-
C function: voidmgl_cones_xyz(HMGL gr, HCDT x, HCDT y, HCDT z, const char *pen, const char *opt)
-
These functions draw cones from points to axis plane. If string contain symbol ‘a’ then cones are drawn one above another (like summation). You can give different colors for positive and negative values if number of specified colors is equal to 2*number of curves. Parameter pen can contain:
-
-
‘@’ for drawing edges;
-
‘#’ for wired cones;
-
‘t’ for drawing tubes/cylinders instead of cones/prisms;
-
‘4’, ‘6’, ‘8’ for drawing square, hex- or octo-prism instead of cones;
-
‘<’, ‘^’ or ‘>’ for aligning boxes left, right or centering them at its x-coordinates.
-
C function: voidmgl_chart(HMGL gr, HCDT a, const char *col, const char *opt)
-
The function draws colored stripes (boxes) for data in array a. The number of stripes is equal to the number of rows in a (equal to a.ny). The color of each next stripe is cyclically changed from colors specified in string col or in palette Pal (see Palette and colors). Spaces in colors denote transparent “color” (i.e. corresponding stripe(s) are not drawn). The stripe width is proportional to value of element in a. Chart is plotted only for data with non-negative elements. If string col have symbol ‘#’ then black border lines are drawn. The most nice form the chart have in 3d (after rotation of coordinates) or in cylindrical coordinates (becomes so called Pie chart). See chart sample, for sample code and picture.
-
C function: voidmgl_boxplot(HMGL gr, HCDT a, const char *pen, const char *opt)
-
C function: voidmgl_boxplot_xy(HMGL gr, HCDT x, HCDT a, const char *pen, const char *opt)
-
These functions draw boxplot (also known as a box-and-whisker diagram) at points x[i]. This is five-number summaries of data a[i,j] (minimum, lower quartile (Q1), median (Q2), upper quartile (Q3) and maximum) along second (j-th) direction. If pen contain ‘<’, ‘^’ or ‘>’ then boxes will be aligned left, right or centered at its x-coordinates. See also plot, error, bars, barwidth. See boxplot sample, for sample code and picture.
-
These functions draw candlestick chart at points x[i]. This is a combination of a line-chart and a bar-chart, in that each bar represents the range of price movement over a given time interval. Wire (or white) candle correspond to price growth v1[i]<v2[i], opposite case – solid (or dark) candle. You can give different colors for growth and decrease values if number of specified colors is equal to 2. If pen contain ‘#’ then the wire candle will be used even for 2-color scheme. "Shadows" show the minimal y1 and maximal y2 prices. If v2 is absent then it is determined as v2[i]=v1[i+1]. See also plot, bars, ohlc, barwidth. See candle sample, for sample code and picture.
-
C function: voidmgl_ohlc(HMGL gr, HCDT o, HCDT h, HCDT l, HCDT c, const char *pen, const char *opt)
-
C function: voidmgl_ohlc_x(HMGL gr, HCDT x, HCDT o, HCDT h, HCDT l, HCDT c, const char *pen, const char *opt)
-
These functions draw Open-High-Low-Close diagram. This diagram show vertical line for between maximal(high h) and minimal(low l) values, as well as horizontal lines before/after vertical line for initial(open o)/final(close c) values of some process (usually price). You can give different colors for up and down values (when closing values higher or not as in previous point) if number of specified colors is equal to 2*number of curves. See also candle, plot, barwidth. See ohlc sample, for sample code and picture.
-
C function: voidmgl_error(HMGL gr, HCDT y, HCDT ey, const char *pen, const char *opt)
-
C function: voidmgl_error_xy(HMGL gr, HCDT x, HCDT y, HCDT ey, const char *pen, const char *opt)
-
C function: voidmgl_error_exy(HMGL gr, HCDT x, HCDT y, HCDT ex, HCDT ey, const char *pen, const char *opt)
-
These functions draw error boxes {ex[i], ey[i]} at points {x[i], y[i]}. This can be useful, for example, in experimental points, or to show numeric error or some estimations and so on. If string pen contain symbol ‘@’ than large semitransparent mark is used instead of error box. See also plot, mark. See error sample, for sample code and picture.
-
C function: voidmgl_mark_y(HMGL gr, HCDT y, HCDT r, const char *pen, const char *opt)
-
C function: voidmgl_mark_xy(HMGL gr, HCDT x, HCDT y, HCDT r, const char *pen, const char *opt)
-
C function: voidmgl_mark_xyz(HMGL gr, HCDT x, HCDT y, HCDT z, HCDT r, const char *pen, const char *opt)
-
These functions draw marks with size r[i]*marksize at points {x[i], y[i], z[i]}. If you need to draw markers of the same size then you can use plot function with empty line style ‘’. For markers with size in axis range use error with style ‘@’. See also plot, textmark, error, stem, meshnum. See mark sample, for sample code and picture.
-
These functions draw string txt as marks with size proportional to r[i]*marksize at points {x[i], y[i], z[i]}. By default (if omitted) r[i]=1. See also plot, mark, stem, meshnum. See textmark sample, for sample code and picture.
-
C function: voidmgl_label(HMGL gr, HCDT y, const char *txt, const char *fnt, const char *opt)
-
C function: voidmgl_labelw(HMGL gr, HCDT y, const wchar_t *txt, const char *fnt, const char *opt)
-
C function: voidmgl_label_xy(HMGL gr, HCDT x, HCDT y, const char *txt, const char *fnt, const char *opt)
-
C function: voidmgl_labelw_xy(HMGL gr, HCDT x, HCDT y, const wchar_t *txt, const char *fnt, const char *opt)
-
C function: voidmgl_label_xyz(HMGL gr, HCDT x, HCDT y, HCDT z, const char *txt, const char *fnt, const char *opt)
-
C function: voidmgl_labelw_xyz(HMGL gr, HCDT x, HCDT y, HCDT z, const wchar_t *txt, const char *fnt, const char *opt)
-
These functions draw string txt at points {x[i], y[i], z[i]}. If string txt contain ‘%x’, ‘%y’, ‘%z’ or ‘%n’ then it will be replaced by the value of x-,y-,z-coordinate of the point or its index. String fnt may contain:
-
Method on mglGraph: voidTable(mreal x, mreal y, const mglDataA &val, const char *txt, const char *fnt="", const char *opt="")
-
Method on mglGraph: voidTable(mreal x, mreal y, const mglDataA &val, const wchar_t *txt, const char *fnt="", const char *opt="")
-
C function: voidmgl_table(HMGL gr, mreal x, mreal y, HCDT val, const char *txt, const char *fnt, const char *opt)
-
C function: voidmgl_tablew(HMGL gr, mreal x, mreal y, HCDT val, const wchar_t *txt, const char *fnt, const char *opt)
-
These functions draw table with values of val and captions from string txt (separated by newline symbol ‘\n’) at points {x, y} (default at {0,0}) related to current subplot. String fnt may contain:
-
Draws Iris plots for determining cross-dependences of data arrays dats (see http://en.wikipedia.org/wiki/Iris_flower_data_set). Data rngs of size 2*dats.nx provide manual axis ranges for each column. String ids contain column names, separated by ‘;’ symbol. Option value set the text size for column names. You can add another data set to existing Iris plot by providing the same ranges rngs and empty column names ids. See also plot. See iris sample, for sample code and picture.
-
C function: voidmgl_tube_r(HMGL gr, HCDT y, HCDT r, const char *pen, const char *opt)
-
C function: voidmgl_tube(HMGL gr, HCDT y, mreal r, const char *pen, const char *opt)
-
C function: voidmgl_tube_xyr(HMGL gr, HCDT x, HCDT y, HCDT r, const char *pen, const char *opt)
-
C function: voidmgl_tube_xy(HMGL gr, HCDT x, HCDT y, mreal r, const char *pen, const char *opt)
-
C function: voidmgl_tube_xyzr(HMGL gr, HCDT x, HCDT y, HCDT z, HCDT r, const char *pen, const char *opt)
-
C function: voidmgl_tube_xyz(HMGL gr, HCDT x, HCDT y, HCDT z, mreal r, const char *pen, const char *opt)
-
These functions draw the tube with variable radius r[i] along the curve between points {x[i], y[i], z[i]}. Option value set the number of segments at cross-section (default is 25). See also plot. See tube sample, for sample code and picture.
-
These functions draw surface which is result of curve {r, z} rotation around axis. If string pen contain symbols ‘x’ or ‘z’ then rotation axis will be set to specified direction (default is ‘y’). If string pen have symbol ‘#’ then wire plot is produced. If string pen have symbol ‘.’ then plot by dots is produced. See also plot, axial. See torus sample, for sample code and picture.
-
These functions draw Lamerey diagram for mapping x_new = y(x_old) starting from point x0. String stl may contain line style, symbol ‘v’ for drawing arrows, symbol ‘~’ for disabling first segment. Option value set the number of segments to be drawn (default is 20). See also plot, fplot, bifurcation, pmap. See lamerey sample, for sample code and picture.
-
These functions draw bifurcation diagram for mapping x_new = y(x_old). Parameter dx set the accuracy along x-direction. String stl set color. Option value set the number of stationary points (default is 1024). See also plot, fplot, lamerey. See bifurcation sample, for sample code and picture.
-
C function: voidmgl_pmap(HMGL gr, HMDT y, HCDT s, const char *stl, const char *opt)
-
C function: voidmgl_pmap_xy(HMGL gr, HCDT x, HMDT y, HCDT s, const char *stl, const char *opt)
-
C function: voidmgl_pmap_xyz(HMGL gr, HCDT x, HMDT y, HCDT z, HCDT s, const char *stl, const char *opt)
-
These functions draw Poincare map for curve {x, y, z} at surface s=0. Basically, it show intersections of the curve and the surface. String stl set the style of marks. See also plot, mark, lamerey. See pmap sample, for sample code and picture.
-
These functions perform plotting of 2D data. 2D means that data depend from 2 independent parameters like matrix f(x_i,y_j), i=1...n, j=1...m. By default (if absent) values of x, y are equidistantly distributed in axis range. The plots are drawn for each z slice of the data. The minor dimensions of arrays x, y, z should be equal x.nx=z.nx && y.nx=z.ny or x.nx=y.nx=z.nx && x.ny=y.ny=z.ny. Arrays x and y can be vectors (not matrices as z). String sch sets the color scheme (see Color scheme) for plot. String opt contain command options (see Command options).
-
C function: voidmgl_surf_xy(HMGL gr, HCDT x, HCDT y, HCDT z, const char *sch, const char *opt)
-
The function draws surface specified parametrically {x[i,j], y[i,j], z[i,j]}. If string sch have symbol ‘#’ then grid lines are drawn. If string sch have symbol ‘.’ then plot by dots is produced. See also mesh, dens, belt, tile, boxs, surfc, surfa. See surf sample, for sample code and picture.
-
C function: voidmgl_mesh_xy(HMGL gr, HCDT x, HCDT y, HCDT z, const char *sch, const char *opt)
-
The function draws mesh lines for surface specified parametrically {x[i,j], y[i,j], z[i,j]}. See also surf, fall, meshnum, cont, tens. See mesh sample, for sample code and picture.
-
C function: voidmgl_fall_xy(HMGL gr, HCDT x, HCDT y, HCDT z, const char *sch, const char *opt)
-
The function draws fall lines for surface specified parametrically {x[i,j], y[i,j], z[i,j]}. This plot can be used for plotting several curves shifted in depth one from another. If sch contain ‘x’ then lines are drawn along x-direction else (by default) lines are drawn along y-direction. See also belt, mesh, tens, meshnum. See fall sample, for sample code and picture.
-
C function: voidmgl_belt_xy(HMGL gr, HCDT x, HCDT y, HCDT z, const char *sch, const char *opt)
-
The function draws belts for surface specified parametrically {x[i,j], y[i,j], z[i,j]}. This plot can be used as 3d generalization of plot). If sch contain ‘x’ then belts are drawn along x-direction else (by default) belts are drawn along y-direction. See also fall, surf, beltc, plot, meshnum. See belt sample, for sample code and picture.
-
C function: voidmgl_boxs_xy(HMGL gr, HCDT x, HCDT y, HCDT z, const char *sch, const char *opt)
-
The function draws vertical boxes for surface specified parametrically {x[i,j], y[i,j], z[i,j]}. Symbol ‘@’ in sch set to draw filled boxes. See also surf, dens, tile, step. See boxs sample, for sample code and picture.
-
C function: voidmgl_tile_xy(HMGL gr, HCDT x, HCDT y, HCDT z, const char *sch, const char *opt)
-
C function: voidmgl_tile_xyc(HMGL gr, HCDT x, HCDT y, HCDT z, HCDT c, const char *sch, const char *opt)
-
The function draws horizontal tiles for surface specified parametrically {x[i,j], y[i,j], z[i,j]} and color it by matrix c[i,j] (c=z if c is not provided). If string sch contain style ‘x’ or ‘y’ then tiles will be oriented perpendicular to x- or y-axis. Such plot can be used as 3d generalization of step. See also surf, boxs, step, tiles. See tile sample, for sample code and picture.
-
C function: voidmgl_dens_xy(HMGL gr, HCDT x, HCDT y, HCDT z, const char *sch, const char *opt)
-
The function draws density plot for surface specified parametrically {x[i,j], y[i,j], z[i,j]} at z equal to minimal z-axis value. If string sch have symbol ‘#’ then grid lines are drawn. If string sch have symbol ‘.’ then plot by dots is produced. See also surf, cont, contf, boxs, tile, dens[xyz]. See dens sample, for sample code and picture.
-
C function: voidmgl_cont_xy_val(HMGL gr, HCDT v, HCDT x, HCDT y, HCDT z, const char *sch, const char *opt)
-
The function draws contour lines for surface specified parametrically {x[i,j], y[i,j], z[i,j]} at z=v[k], or at z equal to minimal z-axis value if sch contain symbol ‘_’. Contours are plotted for z[i,j]=v[k] where v[k] are values of data array v. If string sch have symbol ‘t’ or ‘T’ then contour labels v[k] will be drawn below (or above) the contours. See also dens, contf, contd, axial, cont[xyz]. See cont sample, for sample code and picture.
-
C function: voidmgl_cont_xy(HMGL gr, HCDT x, HCDT y, HCDT z, const char *sch, const char *opt)
-
The same as previous with vector v of num-th elements equidistantly distributed in color range. Here num is equal to parameter value in options opt (default is 7). If string sch contain symbol ‘.’ then only contours at levels with saddle points will be drawn.
-
C function: voidmgl_contf_xy_val(HMGL gr, HCDT v, HCDT x, HCDT y, HCDT z, const char *sch, const char *opt)
-
The function draws solid (or filled) contour lines for surface specified parametrically {x[i,j], y[i,j], z[i,j]} at z=v[k], or at z equal to minimal z-axis value if sch contain symbol ‘_’. Contours are plotted for z[i,j]=v[k] where v[k] are values of data array v (must be v.nx>2). See also dens, cont, contd, contf[xyz]. See contf sample, for sample code and picture.
-
C function: voidmgl_contf_xy(HMGL gr, HCDT x, HCDT y, HCDT z, const char *sch, const char *opt)
-
The same as previous with vector v of num-th elements equidistantly distributed in color range. Here num is equal to parameter value in options opt (default is 7).
-
C function: voidmgl_contd_xy_val(HMGL gr, HCDT v, HCDT x, HCDT y, HCDT z, const char *sch, const char *opt)
-
The function draws solid (or filled) contour lines for surface specified parametrically {x[i,j], y[i,j], z[i,j]} at z=v[k] (or at z equal to minimal z-axis value if sch contain symbol ‘_’) with manual colors. Contours are plotted for z[i,j]=v[k] where v[k] are values of data array v (must be v.nx>2). String sch sets the contour colors: the color of k-th contour is determined by character sch[k%strlen(sch)]. See also dens, cont, contf. See contd sample, for sample code and picture.
-
C function: voidmgl_contd_xy(HMGL gr, HCDT x, HCDT y, HCDT z, const char *sch, const char *opt)
-
The same as previous with vector v of num-th elements equidistantly distributed in color range. Here num is equal to parameter value in options opt (default is 7).
-
C function: voidmgl_contp_val(HMGL gr, HCDT v, HCDT x, HCDT y, HCDT z, HCDT a, const char *sch, const char *opt)
-
The function draws contour lines on surface specified parametrically {x[i,j], y[i,j], z[i,j]}. Contours are plotted for a[i,j]=v[k] where v[k] are values of data array v. If string sch have symbol ‘t’ or ‘T’ then contour labels v[k] will be drawn below (or above) the contours. If string sch have symbol ‘f’ then solid contours will be drawn. See also cont, contf, surfc, cont[xyz].
C function: voidmgl_contp(HMGL gr, HCDT x, HCDT y, HCDT z, HCDT a, const char *sch, const char *opt)
-
The same as previous with vector v of num-th elements equidistantly distributed in color range. Here num is equal to parameter value in options opt (default is 7).
-
C function: voidmgl_contv_xy_val(HMGL gr, HCDT v, HCDT x, HCDT y, HCDT z, const char *sch, const char *opt)
-
The function draws vertical cylinder (tube) at contour lines for surface specified parametrically {x[i,j], y[i,j], z[i,j]} at z=v[k], or at z equal to minimal z-axis value if sch contain symbol ‘_’. Contours are plotted for z[i,j]=v[k] where v[k] are values of data array v. See also cont, contf. See contv sample, for sample code and picture.
-
C function: voidmgl_contv_xy(HMGL gr, HCDT x, HCDT y, HCDT z, const char *sch, const char *opt)
-
The same as previous with vector v of num-th elements equidistantly distributed in color range. Here num is equal to parameter value in options opt (default is 7).
-
C function: voidmgl_axial_xy_val(HMGL gr, HCDT v, HCDT x, HCDT y, HCDT z, const char *sch, const char *opt)
-
The function draws surface which is result of contour plot rotation for surface specified parametrically {x[i,j], y[i,j], z[i,j]}. Contours are plotted for z[i,j]=v[k] where v[k] are values of data array v. If string sch have symbol ‘#’ then wire plot is produced. If string sch have symbol ‘.’ then plot by dots is produced. If string contain symbols ‘x’ or ‘z’ then rotation axis will be set to specified direction (default is ‘y’). See also cont, contf, torus, surf3. See axial sample, for sample code and picture.
-
-
-
-
MGL command: axialzdat ['sch'='']
-
MGL command: axialxdat ydat zdat ['sch'='']
-
Method on mglGraph: voidAxial(const mglDataA &z, const char *sch="", const char *opt="", int num=3)
-
Method on mglGraph: voidAxial(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *sch="", const char *opt="", int num=3)
C function: voidmgl_axial_xy(HMGL gr, HCDT x, HCDT y, HCDT z, const char *sch, const char *opt)
-
The same as previous with vector v of num-th elements equidistantly distributed in color range. Here num is equal to parameter value in options opt (default is 3).
-
C function: voidmgl_grid_xy(HMGL gr, HCDT x, HCDT y, HCDT z, const char *sch, const char *opt)
-
The function draws grid lines for density plot of surface specified parametrically {x[i,j], y[i,j], z[i,j]} at z equal to minimal z-axis value. See also dens, cont, contf, grid3, meshnum.
-
These functions perform plotting of 3D data. 3D means that data depend from 3 independent parameters like matrix f(x_i,y_j,z_k), i=1...n, j=1...m, k=1...l. By default (if absent) values of x, y, z are equidistantly distributed in axis range. The minor dimensions of arrays x, y, z, a should be equal x.nx=a.nx && y.nx=a.ny && z.nz=a.nz or x.nx=y.nx=z.nx=a.nx && x.ny=y.ny=z.ny=a.ny && x.nz=y.nz=z.nz=a.nz. Arrays x, y and z can be vectors (not matrices as a). String sch sets the color scheme (see Color scheme) for plot. String opt contain command options (see Command options).
-
-
-
MGL command: surf3adat val ['sch'='']
-
MGL command: surf3xdat ydat zdat adat val ['sch'='']
C function: voidmgl_surf3_val(HMGL gr, mreal val, HCDT a, const char *sch, const char *opt)
-
C function: voidmgl_surf3_xyz_val(HMGL gr, mreal val, HCDT x, HCDT y, HCDT z, HCDT a, const char *sch, const char *opt)
-
The function draws isosurface plot for 3d array specified parametrically a[i,j,k](x[i,j,k], y[i,j,k], z[i,j,k]) at a(x,y,z)=val. If string contain ‘#’ then wire plot is produced. If string sch have symbol ‘.’ then plot by dots is produced. Note, that there is possibility of incorrect plotting due to uncertainty of cross-section defining if there are two or more isosurface intersections inside one cell. See also cloud, dens3, surf3c, surf3a, axial. See surf3 sample, for sample code and picture.
-
C function: voidmgl_cloud(HMGL gr, HCDT a, const char *sch, const char *opt)
-
C function: voidmgl_cloud_xyz(HMGL gr, HCDT x, HCDT y, HCDT z, HCDT a, const char *sch, const char *opt)
-
The function draws cloud plot for 3d data specified parametrically a[i,j,k](x[i,j,k], y[i,j,k], z[i,j,k]). This plot is a set of cubes with color and transparency proportional to value of a. The resulting plot is like cloud – low value is transparent but higher ones are not. The number of plotting cells depend on meshnum. If string sch contain symbol ‘.’ then lower quality plot will produced with much low memory usage. If string sch contain symbol ‘i’ then transparency will be inversed, i.e. higher become transparent and lower become not transparent. See also surf3, meshnum. See cloud sample, for sample code and picture.
-
C function: voidmgl_dens3(HMGL gr, HCDT a, const char *sch, mreal sVal, const char *opt)
-
C function: voidmgl_dens3_xyz(HMGL gr, HCDT x, HCDT y, HCDT z, HCDT a, const char *sch, mreal sVal, const char *opt)
-
The function draws density plot for 3d data specified parametrically a[i,j,k](x[i,j,k], y[i,j,k], z[i,j,k]). Density is plotted at slice sVal in direction {‘x’, ‘y’, ‘z’} if sch contain corresponding symbol (by default, ‘y’ direction is used). If string stl have symbol ‘#’ then grid lines are drawn. See also cont3, contf3, dens, grid3. See dens3 sample, for sample code and picture.
-
C function: voidmgl_cont3_val(HMGL gr, HCDT v, HCDT a, const char *sch, mreal sVal, const char *opt)
-
C function: voidmgl_cont3_xyz_val(HMGL gr, HCDT v, HCDT x, HCDT y, HCDT z, HCDT a, const char *sch, mreal sVal, const char *opt)
-
The function draws contour plot for 3d data specified parametrically a[i,j,k](x[i,j,k], y[i,j,k], z[i,j,k]). Contours are plotted for values specified in array v at slice sVal in direction {‘x’, ‘y’, ‘z’} if sch contain corresponding symbol (by default, ‘y’ direction is used). If string sch have symbol ‘#’ then grid lines are drawn. If string sch have symbol ‘t’ or ‘T’ then contour labels will be drawn below (or above) the contours. See also dens3, contf3, cont, grid3. See cont3 sample, for sample code and picture.
-
C function: voidmgl_cont3(HMGL gr, HCDT a, const char *sch, mreal sVal, const char *opt)
-
C function: voidmgl_cont3_xyz(HMGL gr, HCDT x, HCDT y, HCDT z, HCDT a, const char *sch, mreal sVal, const char *opt)
-
The same as previous with vector v of num-th elements equidistantly distributed in color range. Here num is equal to parameter value in options opt (default is 7).
-
C function: voidmgl_contf3_val(HMGL gr, HCDT v, HCDT a, const char *sch, mreal sVal, const char *opt)
-
C function: voidmgl_contf3_xyz_val(HMGL gr, HCDT v, HCDT x, HCDT y, HCDT z, HCDT a, const char *sch, mreal sVal, const char *opt)
-
The function draws solid (or filled) contour plot for 3d data specified parametrically a[i,j,k](x[i,j,k], y[i,j,k], z[i,j,k]). Contours are plotted for values specified in array v at slice sVal in direction {‘x’, ‘y’, ‘z’} if sch contain corresponding symbol (by default, ‘y’ direction is used). If string sch have symbol ‘#’ then grid lines are drawn. See also dens3, cont3, contf, grid3. See contf3 sample, for sample code and picture.
-
C function: voidmgl_contf3(HMGL gr, HCDT a, const char *sch, mreal sVal, const char *opt)
-
C function: voidmgl_contf3_xyz(HMGL gr, HCDT x, HCDT y, HCDT z, HCDT a, const char *sch, mreal sVal, const char *opt)
-
The same as previous with vector v of num-th elements equidistantly distributed in color range. Here num is equal to parameter value in options opt (default is 7).
-
C function: voidmgl_grid3(HMGL gr, HCDT a, const char *sch, mreal sVal, const char *opt)
-
C function: voidmgl_grid3_xyz(HMGL gr, HCDT x, HCDT y, HCDT z, HCDT a, const char *sch, mreal sVal, const char *opt)
-
The function draws grid for 3d data specified parametrically a[i,j,k](x[i,j,k], y[i,j,k], z[i,j,k]). Grid is plotted at slice sVal in direction {‘x’, ‘y’, ‘z’} if sch contain corresponding symbol (by default, ‘y’ direction is used). See also cont3, contf3, dens3, grid2, meshnum.
-
C function: voidmgl_beam(HMGL gr, HCDT tr, HCDT g1, HCDT g2, HCDT a, mreal r, const char *stl, int flag, int num)
-
C function: voidmgl_beam_val(HMGL gr, mreal val, HCDT tr, HCDT g1, HCDT g2, HCDT a, mreal r, const char *stl, int flag)
-
Draws the isosurface for 3d array a at constant values of a=val. This is special kind of plot for a specified in accompanied coordinates along curve tr with orts g1, g2 and with transverse scale r. Variable flag is bitwise: ‘0x1’ - draw in accompanied (not laboratory) coordinates; ‘0x2’ - draw projection to \rho-z plane; ‘0x4’ - draw normalized in each slice field. The x-size of data arrays tr, g1, g2 must be nx>2. The y-size of data arrays tr, g1, g2 and z-size of the data array a must be equal. See also surf3.
-
These plotting functions draw two matrix simultaneously. There are 5 generally different types of data representations: surface or isosurface colored by other data (SurfC, Surf3C), surface or isosurface transpared by other data (SurfA, Surf3A), tiles with variable size (TileS), mapping diagram (Map), STFA diagram (STFA). By default (if absent) values of x, y, z are equidistantly distributed in axis range. The minor dimensions of arrays x, y, z, c should be equal. Arrays x, y (and z for Surf3C, Surf3A) can be vectors (not matrices as c). String sch sets the color scheme (see Color scheme) for plot. String opt contain command options (see Command options).
-
C function: voidmgl_surfc_xy(HMGL gr, HCDT x, HCDT y, HCDT z, HCDT c, const char *sch, const char *opt)
-
The function draws surface specified parametrically {x[i,j], y[i,j], z[i,j]} and color it by matrix c[i,j]. If string sch have symbol ‘#’ then grid lines are drawn. If string sch have symbol ‘.’ then plot by dots is produced. All dimensions of arrays z and c must be equal. Surface is plotted for each z slice of the data. See also surf, surfa, surfca, beltc, surf3c. See surfc sample, for sample code and picture.
-
C function: voidmgl_beltc_xy(HMGL gr, HCDT x, HCDT y, HCDT z, const char *sch, const char *opt)
-
The function draws belts for surface specified parametrically {x[i,j], y[i,j], z[i,j]} and color it by matrix c[i,j]. This plot can be used as 3d generalization of plot). If sch contain ‘x’ then belts are drawn along x-direction else (by default) belts are drawn along y-direction. See also belt, surfc, meshnum.
-
-
-
-
-
MGL command: surf3cadat cdat val ['sch'='']
-
MGL command: surf3cxdat ydat zdat adat cdat val ['sch'='']
C function: voidmgl_surf3c_val(HMGL gr, mreal val, HCDT a, HCDT c, const char *sch, const char *opt)
-
C function: voidmgl_surf3c_xyz_val(HMGL gr, mreal val, HCDT x, HCDT y, HCDT z, HCDT a, HCDT c, const char *sch, const char *opt)
-
The function draws isosurface plot for 3d array specified parametrically a[i,j,k](x[i,j,k], y[i,j,k], z[i,j,k]) at a(x,y,z)=val. It is mostly the same as surf3 function but the color of isosurface depends on values of array c. If string sch contain ‘#’ then wire plot is produced. If string sch have symbol ‘.’ then plot by dots is produced. See also surf3, surfc, surf3a, surf3ca. See surf3c sample, for sample code and picture.
-
C function: voidmgl_surfa_xy(HMGL gr, HCDT x, HCDT y, HCDT z, HCDT c, const char *sch, const char *opt)
-
The function draws surface specified parametrically {x[i,j], y[i,j], z[i,j]} and transparent it by matrix c[i,j]. If string sch have symbol ‘#’ then grid lines are drawn. If string sch have symbol ‘.’ then plot by dots is produced. All dimensions of arrays z and c must be equal. Surface is plotted for each z slice of the data. See also surf, surfc, surfca, surf3a. See surfa sample, for sample code and picture.
-
-
-
-
MGL command: surf3aadat cdat val ['sch'='']
-
MGL command: surf3axdat ydat zdat adat cdat val ['sch'='']
C function: voidmgl_surf3a_val(HMGL gr, mreal val, HCDT a, HCDT c, const char *sch, const char *opt)
-
C function: voidmgl_surf3a_xyz_val(HMGL gr, mreal val, HCDT x, HCDT y, HCDT z, HCDT a, HCDT c, const char *sch, const char *opt)
-
The function draws isosurface plot for 3d array specified parametrically a[i,j,k](x[i,j,k], y[i,j,k], z[i,j,k]) at a(x,y,z)=val. It is mostly the same as surf3 function but the transparency of isosurface depends on values of array c. If string sch contain ‘#’ then wire plot is produced. If string sch have symbol ‘.’ then plot by dots is produced. See also surf3, surfc, surf3a, surf3ca. See surf3a sample, for sample code and picture.
-
C function: voidmgl_surf3a(HMGL gr, HCDT a, HCDT c, const char *sch, const char *opt)
-
C function: voidmgl_surf3a_xyz(HMGL gr, HCDT x, HCDT y, HCDT z, HCDT a, HCDT c, const char *sch, const char *opt)
-
Draws num-th uniformly distributed in color range isosurfaces for 3d data. At this array c can be vector with values of transparency and num=c.nx. In opposite case num is equal to parameter value in options opt (default is 3).
-
C function: voidmgl_surfca(HMGL gr, HCDT z, HCDT c, HCDT a, const char *sch, const char *opt)
-
C function: voidmgl_surfca_xy(HMGL gr, HCDT x, HCDT y, HCDT z, HCDT c, HCDT a, const char *sch, const char *opt)
-
The function draws surface specified parametrically {x[i,j], y[i,j], z[i,j]}, color it by matrix c[i,j] and transparent it by matrix a[i,j]. If string sch have symbol ‘#’ then grid lines are drawn. If string sch have symbol ‘.’ then plot by dots is produced. All dimensions of arrays z and c must be equal. Surface is plotted for each z slice of the data. Note, you can use map-like coloring if use ‘%’ in color scheme. See also surf, surfc, surfa, surf3ca. See surfca sample, for sample code and picture.
-
-
-
-
MGL command: surf3caadat cdat bdat val ['sch'='']
-
MGL command: surf3caxdat ydat zdat adat cdat bdat val ['sch'='']
C function: voidmgl_surf3ca_val(HMGL gr, mreal val, HCDT a, HCDT c, HCDT b, const char *sch, const char *opt)
-
C function: voidmgl_surf3ca_xyz_val(HMGL gr, mreal val, HCDT x, HCDT y, HCDT z, HCDT a, HCDT c, HCDT b,const char *sch, const char *opt)
-
The function draws isosurface plot for 3d array specified parametrically a[i,j,k](x[i,j,k], y[i,j,k], z[i,j,k]) at a(x,y,z)=val. It is mostly the same as surf3 function but the color and the transparency of isosurface depends on values of array c and b correspondingly. If string sch contain ‘#’ then wire plot is produced. If string sch have symbol ‘.’ then plot by dots is produced. Note, you can use map-like coloring if use ‘%’ in color scheme. See also surf3, surfca, surf3c, surf3a. See surf3ca sample, for sample code and picture.
-
C function: voidmgl_surf3ca(HMGL gr, HCDT a, HCDT c, HCDT b, const char *sch, const char *opt)
-
C function: voidmgl_surf3ca_xyz(HMGL gr, HCDT x, HCDT y, HCDT z, HCDT a, HCDT c, HCDT b, const char *sch, const char *opt)
-
Draws num-th uniformly distributed in color range isosurfaces for 3d data. Here parameter num is equal to parameter value in options opt (default is 3).
-
C function: voidmgl_tiles_xy(HMGL gr, HCDT x, HCDT y, HCDT z, HCDT r, const char *sch, const char *opt)
-
C function: voidmgl_tiles_xyc(HMGL gr, HCDT x, HCDT y, HCDT z, HCDT r, HCDT c, const char *sch, const char *opt)
-
The function draws horizontal tiles for surface specified parametrically {x[i,j], y[i,j], z[i,j]} and color it by matrix c[i,j]. It is mostly the same as tile but the size of tiles is determined by r array. If string sch contain style ‘x’ or ‘y’ then tiles will be oriented perpendicular to x- or y-axis. This is some kind of “transparency” useful for exporting to EPS files. Tiles is plotted for each z slice of the data. See also surfa, tile. See tiles sample, for sample code and picture.
-
C function: voidmgl_map_xy(HMGL gr, HCDT x, HCDT y, HCDT ax, HCDT ay, const char *sch, const char *opt)
-
The function draws mapping plot for matrices {ax, ay } which parametrically depend on coordinates x, y. The initial position of the cell (point) is marked by color. Height is proportional to Jacobian(ax,ay). This plot is like Arnold diagram ??? If string sch contain symbol ‘.’ then the color ball at matrix knots are drawn otherwise face is drawn. See Mapping visualization, for sample code and picture.
-
-
-
-
MGL command: stfare im dn ['sch'='']
-
MGL command: stfaxdat ydat re im dn ['sch'='']
-
Method on mglGraph: voidSTFA(const mglDataA &re, const mglDataA &im, int dn, const char *sch="", const char *opt="")
C function: voidmgl_stfa(HMGL gr, HCDT re, HCDT im, int dn, const char *sch, const char *opt)
-
C function: voidmgl_stfa_xy(HMGL gr, HCDT x, HCDT y, HCDT re, HCDT im, int dn, const char *sch, const char *opt)
-
Draws spectrogram of complex array re+i*im for Fourier size of dn points at plane z equal to minimal z-axis value. For example in 1D case, result is density plot of data res[i,j]=|\sum_d^dn exp(I*j*d)*(re[i*dn+d]+I*im[i*dn+d])|/dn with size {int(nx/dn), dn, ny}. At this array re, im parametrically depend on coordinates x, y. The size of re and im must be the same. The minor dimensions of arrays x, y, re should be equal. Arrays x, y can be vectors (not matrix as re). See stfa sample, for sample code and picture.
-
These functions perform plotting of 2D and 3D vector fields. There are 5 generally different types of vector fields representations: simple vector field (Vect), vectors along the curve (Traj), vector field by dew-drops (Dew), flow threads (Flow, FlowP), flow pipes (Pipe). By default (if absent) values of x, y, z are equidistantly distributed in axis range. The minor dimensions of arrays x, y, z, ax should be equal. The size of ax, ay and az must be equal. Arrays x, y, z can be vectors (not matrices as ax). String sch sets the color scheme (see Color scheme) for plot. String opt contain command options (see Command options).
-
The function draws vectors {ax, ay, az} along a curve {x, y, z}. The length of arrows are proportional to \sqrt{ax^2+ay^2+az^2}. String pen specifies the color (see Line styles). By default (pen="") color from palette is used (see Palette and colors). Option value set the vector length factor (if non-zero) or vector length to be proportional the distance between curve points (if value=0). The minor sizes of all arrays must be equal and large 2. The plots are drawn for each row if one of the data is the matrix. See also vect. See traj sample, for sample code and picture.
-
C function: voidmgl_vect_xy(HMGL gr, HCDT x, HCDT y, HCDT ax, HCDT ay, const char *sch, const char *opt)
-
The function draws plane vector field plot for the field {ax, ay} depending parametrically on coordinates x, y at level z equal to minimal z-axis value. The length and color of arrows are proportional to \sqrt{ax^2+ay^2}. The number of arrows depend on meshnum. The appearance of the hachures (arrows) can be changed by symbols:
-
-
‘f’ for drawing arrows with fixed lengths,
-
‘>’, ‘<’ for drawing arrows to or from the cell point (default is centering),
-
‘.’ for drawing hachures with dots instead of arrows,
-
C function: voidmgl_vect_3d(HMGL gr, HCDT ax, HCDT ay, HCDT az, const char *sch, const char *opt)
-
C function: voidmgl_vect_xyz(HMGL gr, HCDT x, HCDT y, HCDT z, HCDT ax, HCDT ay, HCDT az, const char *sch, const char *opt)
-
This is 3D version of the first functions. Here arrays ax, ay, az must be 3-ranged tensors with equal sizes and the length and color of arrows is proportional to \sqrt{ax^2+ay^2+az^2}.
-
C function: voidmgl_vect3(HMGL gr, HCDT ax, HCDT ay, HCDT az, const char *sch, mreal sVal, const char *opt)
-
C function: voidmgl_vect3_xyz(HMGL gr, HCDT x, HCDT y, HCDT z, HCDT ax, HCDT ay, HCDT az, const char *sch, mreal sVal, const char *opt)
-
The function draws 3D vector field plot for the field {ax, ay, az} depending parametrically on coordinates x, y, z. Vector field is drawn at slice sVal in direction {‘x’, ‘y’, ‘z’} if sch contain corresponding symbol (by default, ‘y’ direction is used). The length and color of arrows are proportional to \sqrt{ax^2+ay^2+az^2}. The number of arrows depend on meshnum. The appearance of the hachures (arrows) can be changed by symbols:
-
-
‘f’ for drawing arrows with fixed lengths,
-
‘>’, ‘<’ for drawing arrows to or from the cell point (default is centering),
-
‘.’ for drawing hachures with dots instead of arrows,
-
C function: voidmgl_dew_xy(HMGL gr, HCDT x, HCDT y, HCDT ax, HCDT ay, const char *sch, const char *opt)
-
The function draws dew-drops for plane vector field {ax, ay} depending parametrically on coordinates x, y at level z equal to minimal z-axis value. Note that this is very expensive plot in memory usage and creation time! The color of drops is proportional to \sqrt{ax^2+ay^2}. The number of drops depend on meshnum. See also vect. See dew sample, for sample code and picture.
-
C function: voidmgl_flow_xy(HMGL gr, HCDT x, HCDT y, HCDT ax, HCDT ay, const char *sch, const char *opt)
-
The function draws flow threads for the plane vector field {ax, ay} parametrically depending on coordinates x, y at level z equal to minimal z-axis value. Option value set the approximate number of threads (default is 5), or accuracy for stationary points (if style ‘.’ is used) . String sch may contain:
-
-
color scheme – up-half (warm) corresponds to normal flow (like attractor), bottom-half (cold) corresponds to inverse flow (like source);
-
‘#’ for starting threads from edges only;
-
‘.’ for drawing separatrices only (flow threads to/from stationary points).
-
‘*’ for starting threads from a 2D array of points inside the data;
-
‘v’ for drawing arrows on the threads;
-
‘x’, ‘z’ for drawing tapes of normals in x-y and y-z planes correspondingly.
-
C function: voidmgl_flow_3d(HMGL gr, HCDT ax, HCDT ay, HCDT az, const char *sch, const char *opt)
-
C function: voidmgl_flow_xyz(HMGL gr, HCDT x, HCDT y, HCDT z, HCDT ax, HCDT ay, HCDT az, const char *sch, const char *opt)
-
This is 3D version of the first functions. Here arrays ax, ay, az must be 3-ranged tensors with equal sizes and the color of line is proportional to \sqrt{ax^2+ay^2+az^2}.
-
The same as first one (flow) but draws single flow thread starting from point p0={x0,y0,z0}. String sch may also contain: ‘>’ or ‘<’ for drawing in forward or backward direction only (default is both).
-
C function: voidmgl_flow3(HMGL gr, HCDT ax, HCDT ay, HCDT az, const char *sch, double sVal, const char *opt)
-
C function: voidmgl_flow3_xyz(HMGL gr, HCDT x, HCDT y, HCDT z, HCDT ax, HCDT ay, HCDT az, const char *sch, double sVal, const char *opt)
-
The function draws flow threads for the 3D vector field {ax, ay, az} parametrically depending on coordinates x, y, z. Flow threads starts from given plane. Option value set the approximate number of threads (default is 5). String sch may contain:
-
-
color scheme – up-half (warm) corresponds to normal flow (like attractor), bottom-half (cold) corresponds to inverse flow (like source);
-
‘x’, ‘z’ for normal of starting plane (default is y-direction);
-
‘v’ for drawing arrows on the threads;
-
‘t’ for drawing tapes of normals in x-y and y-z planes.
-
C function: voidmgl_grad_xy(HMGL gr, HCDT x, HCDT y, HCDT phi, const char *sch, const char *opt)
-
C function: voidmgl_grad_xyz(HMGL gr, HCDT x, HCDT y, HCDT z, HCDT phi, const char *sch, const char *opt)
-
The function draws gradient lines for scalar field phi[i,j] (or phi[i,j,k] in 3d case) specified parametrically {x[i,j,k], y[i,j,k], z[i,j,k]}. Number of lines is proportional to value option (default is 5). See also dens, cont, flow.
-
C function: voidmgl_pipe_xy(HMGL gr, HCDT x, HCDT y, HCDT ax, HCDT ay, const char *sch, mreal r0, const char *opt)
-
The function draws flow pipes for the plane vector field {ax, ay} parametrically depending on coordinates x, y at level z equal to minimal z-axis value. Number of pipes is proportional to value option (default is 5). If ‘#’ symbol is specified then pipes start only from edges of axis range. The color of lines is proportional to \sqrt{ax^2+ay^2}. Warm color corresponds to normal flow (like attractor). Cold one corresponds to inverse flow (like source). Parameter r0 set the base pipe radius. If r0<0 or symbol ‘i’ is specified then pipe radius is inverse proportional to amplitude. The vector field is plotted for each z slice of ax, ay. See also flow, vect. See pipe sample, for sample code and picture.
-
C function: voidmgl_pipe_3d(HMGL gr, HCDT ax, HCDT ay, HCDT az, const char *sch, mreal r0, const char *opt)
-
C function: voidmgl_pipe_xyz(HMGL gr, HCDT x, HCDT y, HCDT z, HCDT ax, HCDT ay, HCDT az, const char *sch, mreal r0, const char *opt)
-
This is 3D version of the first functions. Here arrays ax, ay, az must be 3-ranged tensors with equal sizes and the color of line is proportional to \sqrt{ax^2+ay^2+az^2}.
-
These functions perform miscellaneous plotting. There is unstructured data points plots (Dots), surface reconstruction (Crust), surfaces on the triangular or quadrangular mesh (TriPlot, TriCont, QuadPlot), textual formula plotting (Plots by formula), data plots at edges (Dens[XYZ], Cont[XYZ], ContF[XYZ]). Each type of plotting has similar interface. There are 2 kind of versions which handle the arrays of data and coordinates or only single data array. Parameters of color scheme are specified by the string argument. See Color scheme.
-
C function: voidmgl_dens_x(HMGL gr, HCDT a, const char *stl, mreal sVal, const char *opt)
-
C function: voidmgl_dens_y(HMGL gr, HCDT a, const char *stl, mreal sVal, const char *opt)
-
C function: voidmgl_dens_z(HMGL gr, HCDT a, const char *stl, mreal sVal, const char *opt)
-
These plotting functions draw density plot in x, y, or z plain. If a is a tensor (3-dimensional data) then interpolation to a given sVal is performed. These functions are useful for creating projections of the 3D data array to the bounding box. See also ContXYZ, ContFXYZ, dens, Data manipulation. See dens_xyz sample, for sample code and picture.
-
C function: voidmgl_cont_x(HMGL gr, HCDT a, const char *stl, mreal sVal, const char *opt)
-
C function: voidmgl_cont_y(HMGL gr, HCDT a, const char *stl, mreal sVal, const char *opt)
-
C function: voidmgl_cont_z(HMGL gr, HCDT a, const char *stl, mreal sVal, const char *opt)
-
These plotting functions draw contour lines in x, y, or z plain. If a is a tensor (3-dimensional data) then interpolation to a given sVal is performed. These functions are useful for creating projections of the 3D data array to the bounding box. Option value set the number of contours. See also ContFXYZ, DensXYZ, cont, Data manipulation. See cont_xyz sample, for sample code and picture.
-
C function: voidmgl_contf_x(HMGL gr, HCDT a, const char *stl, mreal sVal, const char *opt)
-
C function: voidmgl_contf_y(HMGL gr, HCDT a, const char *stl, mreal sVal, const char *opt)
-
C function: voidmgl_contf_z(HMGL gr, HCDT a, const char *stl, mreal sVal, const char *opt)
-
These plotting functions draw solid contours in x, y, or z plain. If a is a tensor (3-dimensional data) then interpolation to a given sVal is performed. These functions are useful for creating projections of the 3D data array to the bounding box. Option value set the number of contours. See also ContFXYZ, DensXYZ, cont, Data manipulation. See contf_xyz sample, for sample code and picture.
-
Draws command function ‘y(x)’ at plane z equal to minimal z-axis value, where ‘x’ variable is changed in xrange. You do not need to create the data arrays to plot it. Option value set initial number of points. See also plot.
-
Draws command parametrical curve {‘x(t)’, ‘y(t)’, ‘z(t)’} where ‘t’ variable is changed in range [0, 1]. You do not need to create the data arrays to plot it. Option value set number of points. See also plot.
-
Draws command surface for function ‘z(x,y)’ where ‘x’, ‘y’ variable are changed in xrange, yrange. You do not need to create the data arrays to plot it. Option value set number of points. See also surf.
-
Draws command parametrical surface {‘x(u,v)’, ‘y(u,v)’, ‘z(u,v)’} where ‘u’, ‘v’ variable are changed in range [0, 1]. You do not need to create the data arrays to plot it. Option value set number of points. See also surf.
-
C function: voidmgl_triplot_xy(HMGL gr, HCDT id, HCDT x, HCDT y, const char *sch, const char *opt)
-
C function: voidmgl_triplot_xyz(HMGL gr, HCDT id, HCDT x, HCDT y, HCDT z, const char *sch, const char *opt)
-
C function: voidmgl_triplot_xyzc(HMGL gr, HCDT id, HCDT x, HCDT y, HCDT z, HCDT c, const char *sch, const char *opt)
-
The function draws the surface of triangles. Triangle vertexes are set by indexes id of data points {x[i], y[i], z[i]}. String sch sets the color scheme. If string contain ‘#’ then wire plot is produced. First dimensions of id must be 3 or greater. Arrays x, y, z must have equal sizes. Parameter c set the colors of triangles (if id.ny=c.nx) or colors of vertexes (if x.nx=c.nx). See also dots, crust, quadplot, triangulation. See triplot sample, for sample code and picture.
-
C function: voidmgl_tricont_xyzv(HMGL gr, HCDT v, HCDT id, HCDT x, HCDT y, HCDT z, const char *sch, const char *opt)
-
The function draws contour lines for surface of triangles at z=v[k] (or at z equal to minimal z-axis value if sch contain symbol ‘_’). Triangle vertexes are set by indexes id of data points {x[i], y[i], z[i]}. Contours are plotted for z[i,j]=v[k] where v[k] are values of data array v. If v is absent then arrays of option value elements equidistantly distributed in color range is used. String sch sets the color scheme. Array c (if specified) is used for contour coloring. First dimensions of id must be 3 or greater. Arrays x, y, z must have equal sizes. Parameter c set the colors of triangles (if id.ny=c.nx) or colors of vertexes (if x.nx=c.nx). See also triplot, cont, triangulation.
-
C function: voidmgl_quadplot_xy(HMGL gr, HCDT id, HCDT x, HCDT y, const char *sch, const char *opt)
-
C function: voidmgl_quadplot_xyz(HMGL gr, HCDT id, HCDT x, HCDT y, HCDT z, const char *sch, const char *opt)
-
C function: voidmgl_quadplot_xyzc(HMGL gr, HCDT id, HCDT x, HCDT y, HCDT z, HCDT c, const char *sch, const char *opt)
-
The function draws the surface of quadrangles. Quadrangles vertexes are set by indexes id of data points {x[i], y[i], z[i]}. String sch sets the color scheme. If string contain ‘#’ then wire plot is produced. First dimensions of id must be 4 or greater. Arrays x, y, z must have equal sizes. Parameter c set the colors of quadrangles (if id.ny=c.nx) or colors of vertexes (if x.nx=c.nx). See also triplot. See triplot sample, for sample code and picture.
-
C function: voidmgl_dots(HMGL gr, HCDT x, HCDT y, HCDT z, const char *sch, const char *opt)
-
C function: voidmgl_dots_a(HMGL gr, HCDT x, HCDT y, HCDT z, HCDT a, const char *sch, const char *opt)
-
C function: voidmgl_dots_ca(HMGL gr, HCDT x, HCDT y, HCDT z, HCDT c, HCDT a, const char *sch, const char *opt)
-
The function draws the arbitrary placed points {x[i], y[i], z[i]}. String sch sets the color scheme and kind of marks. If arrays c, a are specified then they define colors and transparencies of dots. You can use tens plot with style ‘ .’ to draw non-transparent dots with specified colors. Arrays x, y, z, a must have equal sizes. See also crust, tens, mark, plot. See dots sample, for sample code and picture.
-
C function: voidmgl_crust(HMGL gr, HCDT x, HCDT y, HCDT z, const char *sch, const char *opt)
-
The function reconstruct and draws the surface for arbitrary placed points {x[i], y[i], z[i]}. String sch sets the color scheme. If string contain ‘#’ then wire plot is produced. Arrays x, y, z must have equal sizes. See also dots, triplot.
These functions fit data to formula. Fitting goal is to find formula parameters for the best fit the data points, i.e. to minimize the sum \sum_i (f(x_i, y_i, z_i) - a_i)^2/s_i^2. At this, approximation function ‘f’ can depend only on one argument ‘x’ (1D case), on two arguments ‘x,y’ (2D case) and on three arguments ‘x,y,z’ (3D case). The function ‘f’ also may depend on parameters. Normally the list of fitted parameters is specified by var string (like, ‘abcd’). Usually user should supply initial values for fitted parameters by ini variable. But if he/she don’t supply it then the zeros are used. Parameter print=true switch on printing the found coefficients to Message (see Error handling).
-
-
Functions Fit() and FitS() do not draw the obtained data themselves. They fill the data fit by formula ‘f’ with found coefficients and return it. At this, the ‘x,y,z’ coordinates are equidistantly distributed in the axis range. Number of points in fit is defined by option value (default is mglFitPnts=100). Note, that this functions use GSL library and do something only if MathGL was compiled with GSL support. See Nonlinear fitting hints, for sample code and picture.
-
C function: voidmgl_puts_fit(HMGL gr, mreal x, mreal y, mreal z, const char *prefix, const char *font, mreal size)
-
Print last fitted formula with found coefficients (as numbers) at position p0. The string prefix will be printed before formula. All other parameters are the same as in Text printing.
-
-
-
-
Method on mglGraph: const char *GetFit()
-
C function only: const char *mgl_get_fit(HMGL gr)
-
Fortran subroutine: mgl_get_fit(long gr, char *out, int len)
-
Get last fitted formula with found coefficients (as numbers).
-
C function: HMDTmgl_hist_x(HMGL gr, HCDT x, HCDT a, const char *opt)
-
C function: HMDTmgl_hist_xy(HMGL gr, HCDT x, HCDT y, HCDT a, const char *opt)
-
C function: HMDTmgl_hist_xyz(HMGL gr, HCDT x, HCDT y, HCDT z, HCDT a, const char *opt)
-
These functions make distribution (histogram) of data. They do not draw the obtained data themselves. These functions can be useful if user have data defined for random points (for example, after PIC simulation) and he want to produce a plot which require regular data (defined on grid(s)). The range for grids is always selected as axis range. Arrays x, y, z define the positions (coordinates) of random points. Array a define the data value. Number of points in output array res is defined by option value (default is mglFitPnts=100).
-
C function: voidmgl_data_fill_eq(HMGL gr, HMDT u, const char *eq, HCDTv, HCDTw, const char *opt)
-
Fills the value of array ‘u’ according to the formula in string eq. Formula is an arbitrary expression depending on variables ‘x’, ‘y’, ‘z’, ‘u’, ‘v’, ‘w’. Coordinates ‘x’, ‘y’, ‘z’ are supposed to be normalized in axis range. Variable ‘u’ is the original value of the array. Variables ‘v’ and ‘w’ are values of arrays v, w which can be NULL (i.e. can be omitted).
-
C function: voidmgl_data_grid(HMGL gr, HMDT u, HCDT x, HCDT y, HCDT z, const char *opt)
-
Fills the value of array ‘u’ according to the linear interpolation of triangulated surface, found for arbitrary placed points ‘x’, ‘y’, ‘z’. Interpolation is done at points equidistantly distributed in axis range. NAN value is used for grid points placed outside of triangulated surface. See Making regular data, for sample code and picture.
-
-
-
-
MGL command: refilldat xdat vdat [sl=-1]
-
MGL command: refilldat xdat ydat vdat [sl=-1]
-
MGL command: refilldat xdat ydat zdat vdat
-
Method on mglData: voidRefill(mglDataA &dat, const mglDataA &x, const mglDataA &v, long sl=-1, const char *opt="")
-
Method on mglData: voidRefill(mglDataA &dat, const mglDataA &x, const mglDataA &y, const mglDataA &v, long sl=-1, const char *opt="")
C function: voidmgl_data_refill_gr(HMGL gr, HMDT a, HCDT x, HCDT y, HCDT z, HCDT v, long sl, const char *opt)
-
Fills by interpolated values of array v at the point {x, y, z}={X[i], Y[j], Z[k]} (or {x, y, z}={X[i,j,k], Y[i,j,k], Z[i,j,k]} if x, y, z are not 1d arrays), where X,Y,Z are equidistantly distributed in axis range and have the same sizes as array dat. If parameter sl is 0 or positive then changes will be applied only for slice sl.
-
Solves equation du/dz = i*k0*ham(p,q,x,y,z,|u|)[u], where p=-i/k0*d/dx, q=-i/k0*d/dy are pseudo-differential operators. Parameters ini_re, ini_im specify real and imaginary part of initial field distribution. Coordinates ‘x’, ‘y’, ‘z’ are supposed to be normalized in axis range. Note, that really this ranges are increased by factor 3/2 for purpose of reducing reflection from boundaries. Parameter dz set the step along evolutionary coordinate z. At this moment, simplified form of function ham is supported – all “mixed” terms (like ‘x*p’->x*d/dx) are excluded. For example, in 2D case this function is effectively ham = f(p,z) + g(x,z,u). However commutable combinations (like ‘x*q’->x*d/dy) are allowed. Here variable ‘u’ is used for field amplitude |u|. This allow one solve nonlinear problems – for example, for nonlinear Shrodinger equation you may set ham="p^2 + q^2 - u^2". You may specify imaginary part for wave absorption, like ham = "p^2 + i*x*(x>0)", but only if dependence on variable ‘i’ is linear (i.e. ham = hre+i*him). See PDE solving hints, for sample code and picture.
-
There are set of “window” classes for making a window with MathGL graphics: mglWindow, mglFLTK, mglQT and mglGLUT for whole window, Fl_MathGL and QMathGL as widgets. All these classes allow user to show, rotate, export, and change view of the plot using keyboard. Most of them (except mglGLUT) also have toolbar and menu for simplifying plot manipulation. All window classes have mostly the same set of functions derived from mglWnd class.
-
-
For drawing you can use: NULL pointer if you’ll update plot manually, global callback function of type int draw(HMGL gr, void *p) or int draw(mglGraph *gr), or instance of class derived from mglDraw class. Basically, this class have 2 main virtual methods:
-
class mglDraw
-{
-public:
- virtual int Draw(mglGraph *) { return 0; };
- virtual void Reload() {};
-};
-
You should inherit yours class from mglDraw and re-implement one or both functions for drawing.
-
-
The window can be constructed using one of following classes (see Using MathGL window for examples).
-
-
-
Constructor on mglFLTK: mglFLTK(const char *title="MathGL")
Creates a FLTK-based window for plotting. Parameter draw sets a pointer to drawing function (this is the name of function) or instance of mglDraw class. There is support of a list of plots (frames). So as one can prepare a set of frames at first and redraw it fast later (but it requires more memory). Function should return positive number of frames for the list or zero if it will plot directly. Note, that draw can be NULL for displaying static bitmaps only (no animation or slides). Parameter title sets the title of the window. Parameter par contains pointer to data for the plotting function draw. FLTK-based windows is a bit faster than Qt ones, and provide better support of multi-threading.
-
-
-
-
Method on mglFLTK: intRunThr()
-
C function: intmgl_fltk_thr()
-
Run main loop for event handling in separate thread. Note, right now it work for FLTK windows only.
-
-
-
-
-
Constructor on mglQT: mglQT(const char *title="MathGL")
Creates a FLTK-based window for plotting. Parameter draw sets a pointer to drawing function (this is the name of function) or instance of mglDraw class. There is support of a list of plots (frames). So as one can prepare a set of frames at first and redraw it fast later (but it requires more memory). Function should return positive number of frames for the list or zero if it will plot directly. Note, that draw can be NULL for displaying static bitmaps only (no animation or slides). Parameter title sets the title of the window. Parameter par contains pointer to data for the plotting function draw.
-
-
-
-
-
Constructor on mglGLUT: mglGLUT(const char *title="MathGL")
Creates a GLUT-based window for plotting. Parameter draw sets a pointer to drawing function (this is the name of function) or instance of mglDraw class. There is support of a list of plots (frames). So as one can prepare a set of frames at first and redraw it fast later (but it requires more memory). Function should return positive number of frames for the list or zero if it will plot directly. Note, that draw can be NULL for displaying static bitmaps only (no animation or slides). Parameter title sets the title of the window. Parameter par contains pointer to data for the plotting function draw. GLUT-based windows are fastest one but there is no toolbar, and plot have some issues due to OpenGL limitations.
-
-
There are some keys handles for manipulating by the plot: ’a’, ’d’, ’w’, ’s’ for the rotating; ’,’, ’.’ for viewing of the previous or next frames in the list; ’r’ for the switching of transparency; ’f’ for the switching of lightning; ’x’ for hiding (closing) the window.
-
This class is abstract class derived from mglGraph class (see MathGL core). It is defined in #include <mgl2/wnd.h> and provide base methods for handling window with MathGL graphics. Inherited classes are exist for QT and FLTK widget libraries: mglQT in #include <mgl2/qt.h>, mglFLTK in #include <mgl2/fltk.h>.
-
-
-
-
Method on mglWnd: intRun()
-
C function: intmgl_qt_run()
-
C function: intmgl_fltk_run()
-
Run main loop for event handling. Usually it should be called in a separate thread or as last function call in main().
-
This class provide base functionality for callback drawing and running calculation in separate thread. It is defined in #include <mgl2/wnd.h>. You should make inherited class and implement virtual functions if you need it.
-
-
-
Virtual method on mglDraw: intDraw(mglGraph *gr)
-
This is callback drawing function, which will be called when any redrawing is required for the window. There is support of a list of plots (frames). So as one can prepare a set of frames at first and redraw it fast later (but it requires more memory). Function should return positive number of frames for the list or zero if it will plot directly.
-
-
-
-
Virtual method on mglDraw: voidReload()
-
This is callback function, which will be called if user press menu or toolbutton to reload data.
-
-
-
-
Virtual method on mglDraw: voidClick()
-
This is callback function, which will be called if user click mouse.
-
-
-
-
Virtual method on mglDraw: voidCalc()
-
This is callback function, which will be called if user start calculations in separate thread by calling mglDraw::Run() function. It should periodically call mglDraw::Check() function to check if calculations should be paused.
-
-
-
-
Method on mglDraw: voidRun()
-
Runs mglDraw::Calc() function in separate thread. It also initialize mglDraw::thr variable and unlock mglDraw::mutex. Function is present only if FLTK support for widgets was enabled.
-
-
-
-
Method on mglDraw: voidCancel()
-
Cancels thread with calculations. Function is present only if FLTK support for widgets was enabled.
-
-
-
-
Method on mglDraw: voidPause()
-
Pauses thread with calculations by locking mglDraw::mutex. You should call mglDraw::Continue() to continue calculations. Function is present only if FLTK support for widgets was enabled.
-
-
-
-
Method on mglDraw: voidContinue()
-
Continues calculations by unlocking mglDraw::mutex. Function is present only if FLTK support for widgets was enabled.
-
-
-
-
Method on mglDraw: voidContinue()
-
Checks if calculations should be paused and pause it. Function is present only if FLTK support for widgets was enabled.
-
Class is FLTK widget which display MathGL graphics. It is defined in #include <mgl2/Fl_MathGL.h>.
-
-
-
-
-
Method on Fl_MathGL: voidset_draw(int (*draw)(HMGL gr, void *p))
-
Method on Fl_MathGL: voidset_draw(int (*draw)(mglGraph *gr))
-
Method on Fl_MathGL: voidset_draw(mglDraw *draw)
-
Sets drawing function as global function or as one from a class mglDraw. There is support of a list of plots (frames). So as one can prepare a set of frames at first and redraw it fast later (but it requires more memory). Function should return positive number of frames for the list or zero if it will plot directly. Parameter par contains pointer to data for the plotting function draw.
-
-
-
Method on Fl_MathGL: mglDraw *get_class()
-
Get pointer to mglDraw class or NULL if absent.
-
-
-
-
Method on Fl_MathGL: voidupdate()
-
Update (redraw) plot.
-
-
-
Method on Fl_MathGL: voidset_angle(mreal t, mreal p)
-
Set angles for additional plot rotation
-
-
-
Method on Fl_MathGL: voidset_flag(int f)
-
Set bitwise flags for general state (1-Alpha, 2-Light)
-
-
-
Method on Fl_MathGL: voidset_state(bool r, bool z)
-
Set flags for handling mouse:
-z=true allow zooming,
-r=true allow rotation/shifting/perspective and so on.
-
Class is Qt widget which display MathGL graphics. It is defined in #include <mgl2/qt.h>.
-
-
-
-
-
Method on QMathGL: voidsetDraw(mglDraw *dr)
-
Sets drawing functions from a class inherited from mglDraw.
-
-
-
Method on QMathGL: voidsetDraw(int (*draw)(mglBase *gr, void *p), void *par=NULL)
-
Method on QMathGL: voidsetDraw(int (*draw)(mglGraph *gr))
-
Sets the drawing function draw. There is support of a list of plots (frames). So as one can prepare a set of frames at first and redraw it fast later (but it requires more memory). Function should return positive number of frames for the list or zero if it will plot directly. Parameter par contains pointer to data for the plotting function draw.
-
-
-
-
Method on QMathGL: voidsetGraph(HMGL gr)
-
Method on QMathGL: voidsetGraph(mglGraph *gr)
-
Set pointer to external grapher (instead of built-in one). Note that QMathGL will automatically delete this object at destruction or at new setGraph() call.
-
-
-
Method on QMathGL: HMGLgetGraph()
-
Get pointer to grapher.
-
-
-
-
Method on QMathGL: voidsetPopup(QMenu *p)
-
Set popup menu pointer.
-
-
-
Method on QMathGL: voidsetSize(int w, int h)
-
Set widget/picture sizes
-
-
-
Method on QMathGL: doublegetRatio()
-
Return aspect ratio of the picture.
-
-
-
-
Method on QMathGL: intgetPer()
-
Get perspective value in percents.
-
-
-
Method on QMathGL: intgetPhi()
-
Get Phi-angle value in degrees.
-
-
-
Method on QMathGL: intgetTet()
-
Get Theta-angle value in degrees.
-
-
-
Method on QMathGL: boolgetAlpha()
-
Get transparency state.
-
-
-
Method on QMathGL: boolgetLight()
-
Get lightning state.
-
-
-
Method on QMathGL: boolgetZoom()
-
Get mouse zooming state.
-
-
-
Method on QMathGL: boolgetRotate()
-
Get mouse rotation state.
-
-
-
-
-
Slot on QMathGL: voidrefresh()
-
Redraw saved bitmap without executing drawing function.
-
-
-
Slot on QMathGL: voidupdate()
-
Update picture by executing drawing function.
-
-
-
Slot on QMathGL: voidcopy()
-
Copy graphics to clipboard.
-
-
-
Slot on QMathGL: voidcopyClickCoor()
-
Copy coordinates of click (as text).
-
-
-
Slot on QMathGL: voidprint()
-
Print current picture.
-
-
-
-
Slot on QMathGL: voidstop()
-
Send signal to stop drawing.
-
-
-
Slot on QMathGL: voidadjust()
-
Adjust image size to fit whole widget.
-
-
-
Slot on QMathGL: voidnextSlide()
-
Show next slide.
-
-
-
Slot on QMathGL: voidprevSlide()
-
Show previous slide.
-
-
-
Slot on QMathGL: voidanimation(bool st=true)
-
Start/stop animation.
-
-
-
-
Slot on QMathGL: voidsetPer(int val)
-
Set perspective value.
-
-
-
Slot on QMathGL: voidsetPhi(int val)
-
Set Phi-angle value.
-
-
-
Slot on QMathGL: voidsetTet(int val)
-
Set Theta-angle value.
-
-
-
Slot on QMathGL: voidsetAlpha(bool val)
-
Switch on/off transparency.
-
-
-
Slot on QMathGL: voidsetLight(bool val)
-
Switch on/off lightning.
-
-
-
Slot on QMathGL: voidsetGrid(bool val)
-
Switch on/off drawing of grid for absolute coordinates.
-
-
-
Slot on QMathGL: voidsetZoom(bool val)
-
Switch on/off mouse zooming.
-
-
-
Slot on QMathGL: voidsetRotate(bool val)
-
Switch on/off mouse rotation.
-
-
-
Slot on QMathGL: voidzoomIn()
-
Zoom in graphics.
-
-
-
Slot on QMathGL: voidzoomOut()
-
Zoom out graphics.
-
-
-
Slot on QMathGL: voidshiftLeft()
-
Shift graphics to left direction.
-
-
-
Slot on QMathGL: voidshiftRight()
-
Shift graphics to right direction.
-
-
-
Slot on QMathGL: voidshiftUp()
-
Shift graphics to up direction.
-
-
-
Slot on QMathGL: voidshiftDown()
-
Shift graphics to down direction.
-
-
-
Slot on QMathGL: voidrestore()
-
Restore zoom and rotation to default values.
-
-
-
-
Slot on QMathGL: voidexportPNG(QString fname="")
-
Export current picture to PNG file.
-
-
-
Slot on QMathGL: voidexportPNGs(QString fname="")
-
Export current picture to PNG file (no transparency).
-
-
-
Slot on QMathGL: voidexportJPG(QString fname="")
-
Export current picture to JPEG file.
-
-
-
Slot on QMathGL: voidexportBPS(QString fname="")
-
Export current picture to bitmap EPS file.
-
-
-
Slot on QMathGL: voidexportEPS(QString fname="")
-
Export current picture to vector EPS file.
-
-
-
Slot on QMathGL: voidexportSVG(QString fname="")
-
Export current picture to SVG file.
-
-
-
-
Slot on QMathGL: voidexportGIF(QString fname="")
-
Export current picture to GIF file.
-
-
-
Slot on QMathGL: voidexportTEX(QString fname="")
-
Export current picture to LaTeX/Tikz file.
-
-
-
Slot on QMathGL: voidexportTGA(QString fname="")
-
Export current picture to TGA file.
-
-
-
-
Slot on QMathGL: voidexportXYZ(QString fname="")
-
Export current picture to XYZ/XYZL/XYZF file.
-
-
-
Slot on QMathGL: voidexportOBJ(QString fname="")
-
Export current picture to OBJ/MTL file.
-
-
-
Slot on QMathGL: voidexportSTL(QString fname="")
-
Export current picture to STL file.
-
-
-
Slot on QMathGL: voidexportOFF(QString fname="")
-
Export current picture to OFF file.
-
-
-
-
Slot on QMathGL: voidsetUsePrimitives(booluse)
-
Enable using list of primitives for frames. This allows frames transformation/zoom but requires much more memory. Default value is true.
-
-
-
Slot on QMathGL: voidsetMGLFont(QString path)
-
Restore (path="") or load font for graphics.
-
-
-
-
Slot on QMathGL: voidabout()
-
Show about information.
-
-
-
Slot on QMathGL: voidaboutQt()
-
Show information about Qt version.
-
-
-
-
Signal on QMathGL: voidphiChanged(int val)
-
Phi angle changed (by mouse or by toolbar).
-
-
-
Signal on QMathGL: voidtetChanged(int val)
-
Tet angle changed (by mouse or by toolbar).
-
-
-
Signal on QMathGL: voidperChanged(int val)
-
Perspective changed (by mouse or by toolbar).
-
-
-
Signal on QMathGL: voidalphaChanged(bool val)
-
Transparency changed (by toolbar).
-
-
-
Signal on QMathGL: voidlightChanged(bool val)
-
Lighting changed (by toolbar).
-
-
-
Signal on QMathGL: voidgridChanged(bool val)
-
Grid drawing changed (by toolbar).
-
-
-
Signal on QMathGL: voidzoomChanged(bool val)
-
Zooming changed (by toolbar).
-
-
-
Signal on QMathGL: voidrotateChanged(bool val)
-
Rotation changed (by toolbar).
-
-
-
-
Signal on QMathGL: voidmouseClick(mreal x, mreal y, mreal z)
Class is WX widget which display MathGL graphics. It is defined in #include <mgl2/wx.h>.
-
-
-
Method on wxMathGL: voidSetDraw(mglDraw *dr)
-
Sets drawing functions from a class inherited from mglDraw.
-
-
-
Method on wxMathGL: voidSetDraw(int (*draw)(mglBase *gr, void *p), void *par=NULL)
-
Method on wxMathGL: voidSetDraw(int (*draw)(mglGraph *gr))
-
Sets the drawing function draw. There is support of a list of plots (frames). So as one can prepare a set of frames at first and redraw it fast later (but it requires more memory). Function should return positive number of frames for the list or zero if it will plot directly. Parameter par contains pointer to data for the plotting function draw.
-
-
-
-
Method on wxMathGL: voidSetGraph(HMGL gr)
-
Method on wxMathGL: voidSetGraph(mglGraph *gr)
-
Set pointer to external grapher (instead of built-in one). Note that wxMathGL will automatically delete this object at destruction or at new setGraph() call.
-
-
-
Method on wxMathGL: HMGLGetGraph()
-
Get pointer to grapher.
-
-
-
-
Method on wxMathGL: voidSetPopup(wxMenu *p)
-
Set popup menu pointer.
-
-
-
Method on wxMathGL: voidSetSize(int w, int h)
-
Set widget/picture sizes
-
-
-
Method on wxMathGL: doubleGetRatio()
-
Return aspect ratio of the picture.
-
-
-
-
Method on wxMathGL: intGetPer()
-
Get perspective value in percents.
-
-
-
Method on wxMathGL: intGetPhi()
-
Get Phi-angle value in degrees.
-
-
-
Method on wxMathGL: intGetTet()
-
Get Theta-angle value in degrees.
-
-
-
Method on wxMathGL: boolGetAlpha()
-
Get transparency state.
-
-
-
Method on wxMathGL: boolGetLight()
-
Get lightning state.
-
-
-
Method on wxMathGL: boolGetZoom()
-
Get mouse zooming state.
-
-
-
Method on wxMathGL: boolGetRotate()
-
Get mouse rotation state.
-
-
-
-
-
Method on wxMathGL: voidRepaint()
-
Redraw saved bitmap without executing drawing function.
-
-
-
Method on wxMathGL: voidUpdate()
-
Update picture by executing drawing function.
-
-
-
Method on wxMathGL: voidCopy()
-
Copy graphics to clipboard.
-
-
-
Method on wxMathGL: voidPrint()
-
Print current picture.
-
-
-
-
Method on wxMathGL: voidAdjust()
-
Adjust image size to fit whole widget.
-
-
-
Method on wxMathGL: voidNextSlide()
-
Show next slide.
-
-
-
Method on wxMathGL: voidPrevSlide()
-
Show previous slide.
-
-
-
Method on wxMathGL: voidAnimation(bool st=true)
-
Start/stop animation.
-
-
-
-
Method on wxMathGL: voidSetPer(int val)
-
Set perspective value.
-
-
-
Method on wxMathGL: voidSetPhi(int val)
-
Set Phi-angle value.
-
-
-
Method on wxMathGL: voidSetTet(int val)
-
Set Theta-angle value.
-
-
-
Method on wxMathGL: voidSetAlpha(bool val)
-
Switch on/off transparency.
-
-
-
Method on wxMathGL: voidSetLight(bool val)
-
Switch on/off lightning.
-
-
-
Method on wxMathGL: voidSetZoom(bool val)
-
Switch on/off mouse zooming.
-
-
-
Method on wxMathGL: voidSetRotate(bool val)
-
Switch on/off mouse rotation.
-
-
-
Method on wxMathGL: voidZoomIn()
-
Zoom in graphics.
-
-
-
Method on wxMathGL: voidZoomOut()
-
Zoom out graphics.
-
-
-
Method on wxMathGL: voidShiftLeft()
-
Shift graphics to left direction.
-
-
-
Method on wxMathGL: voidShiftRight()
-
Shift graphics to right direction.
-
-
-
Method on wxMathGL: voidShiftUp()
-
Shift graphics to up direction.
-
-
-
Method on wxMathGL: voidShiftDown()
-
Shift graphics to down direction.
-
-
-
Method on wxMathGL: voidRestore()
-
Restore zoom and rotation to default values.
-
-
-
-
Method on wxMathGL: voidAbout()
-
Show about information.
-
-
-
-
Method on wxMathGL: voidExportPNG(QString fname="")
-
Export current picture to PNG file.
-
-
-
Method on wxMathGL: voidExportPNGs(QString fname="")
-
Export current picture to PNG file (no transparency).
-
-
-
Method on wxMathGL: voidExportJPG(QString fname="")
-
Export current picture to JPEG file.
-
-
-
Method on wxMathGL: voidExportBPS(QString fname="")
-
Export current picture to bitmap EPS file.
-
-
-
Method on wxMathGL: voidExportEPS(QString fname="")
-
Export current picture to vector EPS file.
-
-
-
Method on wxMathGL: voidExportSVG(QString fname="")
This chapter describe classes mglData and mglDataC for working with data arrays of real and complex numbers. Both classes are derived from abstract class mglDataA, and can be used as arguments of any plotting functions (see MathGL core). These classes are defined in #include <mgl2/data.h> and #include <mgl2/datac.h> correspondingly. The classes have mostly the same set of functions for easy and safe allocation, resizing, loading, saving, modifying of data arrays. Also it can numerically differentiate and integrate data, interpolate, fill data by formula and so on. Classes support data with dimensions up to 3 (like function of 3 variables – x,y,z). The internal representation of numbers is mreal (or dual=std::complex<mreal> for mglDataC), which can be configured as float or double by selecting option --enable-double at the MathGL configuring (see Installation). Float type have smaller size in memory and usually it has enough precision in plotting purposes. However, double type provide high accuracy what can be important for time-axis, for example. Data arrays are denoted by Small Caps (like DAT) if it can be (re-)created by MGL commands.
-
Data array itself. The flat data representation is used. For example, matrix [nx x ny] is presented as flat (1d-) array with length nx*ny. The element with indexes {i, j, k} is a[i+nx*j+nx*ny*k] (indexes are zero based).
-
-
-
Variable of mglData: longnx
-
Variable of mglDataC: longnx
-
Number of points in 1st dimensions (’x’ dimension).
-
-
-
Variable of mglData: longny
-
Variable of mglDataC: longny
-
Number of points in 2nd dimensions (’y’ dimension).
-
-
-
Variable of mglData: longnz
-
Variable of mglDataC: longnz
-
Number of points in 3d dimensions (’z’ dimension).
-
-
-
Variable of mglData: std::stringid
-
Variable of mglDataC: std::stringid
-
Names of column (or slice if nz>1) – one character per column.
-
-
-
Variable of mglData: boollink
-
Variable of mglDataC: boollink
-
Flag to use external data, i.e. don’t delete it.
-
-
-
-
Variable of mglDataA: std::wstrings
-
Name of data. It is used in parsing of MGL scripts.
-
-
-
Variable of mglDataA: booltemp
-
Flag of temporary variable, which should be deleted.
-
-
-
Variable of mglDataA: void (*)(void *)func
-
Pointer to callback function which will be called at destroying.
-
-
-
Variable of mglDataA: void *o
-
Pointer to object for callback function.
-
-
-
-
-
Method on mglData: mrealGetVal(long i)
-
Method on mglDataC: mrealGetVal(long i)
-
Method on mglData: voidSetVal(mreal val, long i)
-
Method on mglDataC: voidSetVal(mreal val, long i)
-
Gets or sets the value in by "flat" index i without border checking. Index i should be in range [0, nx*ny*nz-1].
-
-
-
-
Method on mglDataA: longGetNx()
-
Method on mglDataA: longGetNy()
-
Method on mglDataA: longGetNz()
-
C function: longmgl_data_get_nx(HCDT dat)
-
C function: longmgl_data_get_ny(HCDT dat)
-
C function: longmgl_data_get_nz(HCDT dat)
-
Gets the x-, y-, z-size of the data.
-
-
-
-
C function: mrealmgl_data_get_value(HCDT dat, int i, int j, int k)
-
C function: dualmgl_datac_get_value(HCDT dat, int i, int j, int k)
-
C function: mreal *mgl_data_value(HMDT dat, int i, int j, int k)
-
C function: dual *mgl_datac_value(HADT dat, int i, int j, int k)
-
C function: voidmgl_data_set_value(HMDT dat, mreal v, int i, int j, int k)
-
C function: voidmgl_datac_set_value(HADT dat, dual v, int i, int j, int k)
-
Gets or sets the value in specified cell of the data with border checking.
-
-
-
C function: const mreal *mgl_data_data(HCDT dat)
-
C function: const dual *mgl_datac_data(HCDT dat)
-
Returns pointer to internal data array.
-
-
-
-
C function only: voidmgl_data_set_func(mglDataA *dat, void (*func)(void *), void *par)
-
Set pointer to callback function which will be called at destroying.
-
-
-
-
C function: voidmgl_data_set_name(mglDataA *dat, const char *name)
-
C function: voidmgl_data_set_name_w(mglDataA *dat, const wchar_t *name)
-
Set name of data, which used in parsing of MGL scripts.
-
Constructor on mglData: mglData(int mx=1, int my=1, int mz=1)
-
Constructor on mglDataC: mglDataC(int mx=1, int my=1, int mz=1)
-
C function: HMDTmgl_create_data()
-
C function: HMDTmgl_create_data_size(int mx, int my, int mz)
-
C function: HADTmgl_create_datac()
-
C function: HADTmgl_create_datac_size(int mx, int my, int mz)
-
Default constructor. Allocates the memory for data array and initializes it by zero. If string eq is specified then data will be filled by corresponding formula as in fill.
-
-
-
-
MGL command: copyDAT dat2 ['eq'='']
-
MGL command: copyDAT val
-
Constructor on mglData: mglData(const mglDataA &dat2)
-
Constructor on mglData: mglData(const mglDataA *dat2)
-
Constructor on mglData: mglData(int size, const float *dat2)
-
Constructor on mglData: mglData(int size, int cols, const float *dat2)
-
Constructor on mglData: mglData(int size, const double *dat2)
-
Constructor on mglData: mglData(int size, int cols, const double *dat2)
-
Constructor on mglData: mglData(const double *dat2, int size)
-
Constructor on mglData: mglData(const double *dat2, int size, int cols)
-
Constructor on mglDataC: mglDataC(const mglDataA &dat2)
-
Constructor on mglDataC: mglDataC(const mglDataA *dat2)
-
Constructor on mglDataC: mglDataC(int size, const float *dat2)
-
Constructor on mglDataC: mglDataC(int size, int cols, const float *dat2)
-
Constructor on mglDataC: mglDataC(int size, const double *dat2)
-
Constructor on mglDataC: mglDataC(int size, int cols, const double *dat2)
-
Constructor on mglDataC: mglDataC(int size, const dual *dat2)
-
Constructor on mglDataC: mglDataC(int size, int cols, const dual *dat2)
-
Copy constructor. Allocates the memory for data array and copy values from other array. At this, if parameter eq or val is specified then the data will be modified by corresponding formula similarly to fill.
-
-
-
-
MGL command: copyREDAT IMDAT dat2 ['eq'='']
-
Allocates the memory for data array and copy real and imaginary values from complex array dat2.
-
-
-
-
MGL command: copy'name'
-
Allocates the memory for data array and copy values from other array specified by its name, which can be "invalid" for MGL names (like one read from HDF5 files).
-
-
-
-
-
MGL command: readDAT 'fname'
-
Constructor on mglData: mglData(const char *fname)
-
Constructor on mglDataC: mglDataC(const char *fname)
-
C function: HMDTmgl_create_data_file(const char *fname)
-
C function: HADTmgl_create_datac_file(const char *fname)
-
Reads data from tab-separated text file with auto determining sizes of the data.
-
Method on mglData: voidCreate(int mx, int my=1, int mz=1)
-
Method on mglDataC: voidCreate(int mx, int my=1, int mz=1)
-
C function: voidmgl_data_create(HMDT dat, int mx, int my, int mz)
-
C function: voidmgl_datac_create(HADT dat, int mx, int my, int mz)
-
Creates or recreates the array with specified size and fills it by zero. This function does nothing if one of parameters mx, my, mz is zero or negative.
-
-
-
-
MGL command: rearrangedat mx [my=0 mz=0]
-
Method on mglData: voidRearrange(int mx, int my=0, int mz=0)
-
Method on mglDataC: voidRearrange(int mx, int my=0, int mz=0)
-
C function: voidmgl_data_rearrange(HMDT dat, int mx, int my, int mz)
-
C function: voidmgl_datac_rearrange(HADT dat, int mx, int my, int mz)
-
Rearrange dimensions without changing data array so that resulting sizes should be mx*my*mz < nx*ny*nz. If some of parameter my or mz are zero then it will be selected to optimal fill of data array. For example, if my=0 then it will be change to my=nx*ny*nz/mx and mz=1.
-
-
-
-
MGL command: transposedat ['dim'='yxz']
-
Method on mglData: voidTranspose(const char *dim="yx")
-
Method on mglDataC: voidTranspose(const char *dim="yx")
-
C function: voidmgl_data_transpose(HMDT dat, const char *dim)
-
C function: voidmgl_datac_transpose(HADT dat, const char *dim)
-
Transposes (shift order of) dimensions of the data. New order of dimensions is specified in string dim. This function can be useful also after reading of one-dimensional data.
-
-
-
-
MGL command: extenddat n1 [n2=0]
-
Method on mglData: voidExtend(int n1, int n2=0)
-
Method on mglDataC: voidExtend(int n1, int n2=0)
-
C function: voidmgl_data_extend(HMDT dat, int n1, int n2)
-
C function: voidmgl_datac_extend(HADT dat, int n1, int n2)
-
Increase the dimensions of the data by inserting new (|n1|+1)-th slices after (for n1>0) or before (for n1<0) of existed one. It is possible to insert 2 dimensions simultaneously for 1d data by using parameter n2. Data to new slices is copy from existed one. For example, for n1>0 new array will be
-a_ij^new = a_i^old where j=0...n1. Correspondingly, for n1<0 new array will be a_ij^new = a_j^old where i=0...|n1|.
-
-
-
-
MGL command: squeezedat rx [ry=1 rz=1 sm=off]
-
Method on mglData: voidSqueeze(int rx, int ry=1, int rz=1, bool smooth=false)
-
Method on mglDataC: voidSqueeze(int rx, int ry=1, int rz=1, bool smooth=false)
-
C function: voidmgl_data_squeeze(HMDT dat, int rx, int ry, int rz, int smooth)
-
C function: voidmgl_datac_squeeze(HADT dat, int rx, int ry, int rz, int smooth)
-
Reduces the data size by excluding data elements which indexes are not divisible by rx, ry, rz correspondingly. Parameter smooth set to use smoothing
-(i.e. out[i]=\sum_{j=i,i+r} a[j]/r) or not (i.e. out[i]=a[j*r]).
-
-
-
-
MGL command: cropdat n1 n2 'dir'
-
Method on mglData: voidCrop(int n1, int n2, char dir='x')
-
Method on mglDataC: voidCrop(int n1, int n2, char dir='x')
-
C function: voidmgl_data_crop(HMDT dat, int n1, int n2, char dir)
-
C function: voidmgl_datac_crop(HADT dat, int n1, int n2, char dir)
-
Cuts off edges of the data i<n1 and i>n2 if n2>0 or i>n[xyz]-n2 if n2<=0 along direction dir.
-
-
-
-
MGL command: cropdat 'how'
-
Method on mglData: voidCrop(const char *how="235x")
-
Method on mglDataC: voidCrop(const char *how="235x")
-
C function: voidmgl_data_crop_opt(HMDT dat, const char *how)
-
C function: voidmgl_datac_crop_opt(HADT dat, const char *how)
-
Cuts off far edge of the data to be more optimal for fast Fourier transform. The resulting size will be the closest value of 2^n*3^m*5^l to the original one. The string how may contain: ‘x’, ‘y’, ‘z’ for directions, and ‘2’, ‘3’, ‘5’ for using corresponding bases.
-
-
-
-
MGL command: insertdat 'dir' [pos=off num=0]
-
Method on mglData: voidInsert(char dir, int pos=0, int num=1)
-
Method on mglDataC: voidInsert(char dir, int pos=0, int num=1)
-
C function: voidmgl_data_insert(HMDT dat, char dir, int pos, char num)
-
C function: voidmgl_datac_insert(HADT dat, char dir, int pos, char num)
-
Insert num slices along dir-direction at position pos and fill it by zeros.
-
-
-
-
MGL command: deletedat 'dir' [pos=off num=0]
-
Method on mglData: voidDelete(char dir, int pos=0, int num=1)
-
Method on mglDataC: voidDelete(char dir, int pos=0, int num=1)
-
C function: voidmgl_data_delete(HMDT dat, char dir, int pos, char num)
-
C function: voidmgl_datac_delete(HADT dat, char dir, int pos, char num)
-
Delete num slices along dir-direction at position pos.
-
-
-
-
MGL command: deletedat
-
MGL command: delete'name'
-
Deletes the whole data array.
-
-
-
-
MGL command: sortdat idx [idy=-1]
-
Method on mglData: voidSort(lond idx, long idy=-1)
-
C function: voidmgl_data_sort(HMDT dat, lond idx, long idy)
-
Sort data rows (or slices in 3D case) by values of specified column idx (or cell {idx,idy} for 3D case). Note, this function is not thread safe!
-
-
-
-
MGL command: cleandat idx
-
Method on mglData: voidClean(lond idx)
-
C function: voidmgl_data_clean(HMDT dat, lond idx)
-
Delete rows which values are equal to next row for given column idx.
-
-
-
-
MGL command: joindat vdat [v2dat ...]
-
Method on mglData: voidJoin(const mglDataA &vdat)
-
Method on mglDataC: voidJoin(const mglDataA &vdat)
-
C function: voidmgl_data_join(HMDT dat, HCDT vdat)
-
C function: voidmgl_datac_join(HADT dat, HCDT vdat)
-
Join data cells from vdat to dat. At this, function increase dat sizes according following: z-size for data arrays arrays with equal x-,y-sizes; or y-size for data arrays with equal x-sizes; or x-size otherwise.
-
Creates new variable with name dat and fills it by numeric values of command arguments v1 .... Command can create one-dimensional and two-dimensional arrays with arbitrary values. For creating 2d array the user should use delimiter ‘|’ which means that the following values lie in next row. Array sizes are [maximal of row sizes * number of rows]. For example, command list 1 | 2 3 creates the array [1 0; 2 3]. Note, that the maximal number of arguments is 1000.
-
-
-
MGL command: listDAT d1 ...
-
Creates new variable with name dat and fills it by data values of arrays of command arguments d1 .... Command can create two-dimensional or three-dimensional (if arrays in arguments are 2d arrays) arrays with arbitrary values. Minor dimensions of all arrays in arguments should be equal to dimensions of first array d1. In the opposite case the argument will be ignored. Note, that the maximal number of arguments is 1000.
-
-
-
-
Method on mglData: voidSet(const float *A, int NX, int NY=1, int NZ=1)
-
Method on mglData: voidSet(const double *A, int NX, int NY=1, int NZ=1)
-
C function: voidmgl_data_set_float(HMDT dat, const mreal *A, int NX, int NY, int NZ)
-
C function: voidmgl_data_set_double(HMDT dat, const double *A, int NX, int NY, int NZ)
-
Method on mglDataC: voidSet(const float *A, int NX, int NY=1, int NZ=1)
-
Method on mglDataC: voidSet(const double *A, int NX, int NY=1, int NZ=1)
-
Method on mglDataC: voidSet(const dual *A, int NX, int NY=1, int NZ=1)
-
C function: voidmgl_datac_set_float(HADT dat, const mreal *A, int NX, int NY, int NZ)
-
C function: voidmgl_datac_set_double(HADT dat, const double *A, int NX, int NY, int NZ)
-
C function: voidmgl_datac_set_complex(HADT dat, const dual *A, int NX, int NY, int NZ)
-
Allocates memory and copies the data from the flatfloat* or double* array.
-
-
-
-
Method on mglData: voidSet(const float **A, int N1, int N2)
-
Method on mglData: voidSet(const double **A, int N1, int N2)
-
C function: voidmgl_data_set_mreal2(HMDT dat, const mreal **A, int N1, int N2)
-
C function: voidmgl_data_set_double2(HMDT dat, const double **A, int N1, int N2)
-
Allocates memory and copies the data from the float** or double** array with dimensions N1, N2, i.e. from array defined as mreal a[N1][N2];.
-
-
-
-
Method on mglData: voidSet(const float ***A, int N1, int N2)
-
Method on mglData: voidSet(const double ***A, int N1, int N2)
-
C function: voidmgl_data_set_mreal3(HMDT dat, const mreal ***A, int N1, int N2)
-
C function: voidmgl_data_set_double3(HMDT dat, const double ***A, int N1, int N2)
-
Allocates memory and copies the data from the float*** or double*** array with dimensions N1, N2, N3, i.e. from array defined as mreal a[N1][N2][N3];.
-
-
-
-
Method on mglData: voidSet(gsl_vector *v)
-
Method on mglDataC: voidSet(gsl_vector *v)
-
C function: voidmgl_data_set_vector(HMDT dat, gsl_vector *v)
-
C function: voidmgl_datac_set_vector(HADT dat, gsl_vector *v)
-
Allocates memory and copies the data from the gsl_vector * structure.
-
-
-
Method on mglData: voidSet(gsl_matrix *m)
-
Method on mglDataC: voidSet(gsl_matrix *m)
-
C function: voidmgl_data_set_matrix(HMDT dat, gsl_matrix *m)
-
C function: voidmgl_datac_set_matrix(HADT dat, gsl_matrix *m)
-
Allocates memory and copies the data from the gsl_matrix * structure.
-
-
-
-
Method on mglData: voidSet(const mglDataA &from)
-
Method on mglData: voidSet(HCDT from)
-
C function: voidmgl_data_set(HMDT dat, HCDT from)
-
Method on mglDataC: voidSet(const mglDataA &from)
-
Method on mglDataC: voidSet(HCDT from)
-
C function: voidmgl_datac_set(HADT dat, HCDT from)
-
Copies the data from mglData (or mglDataA) instance from.
-
-
-
-
Method on mglDataC: voidSet(const mglDataA &re, const mglDataA &im)
-
Method on mglDataC: voidSet(HCDT re, HCDT im)
-
Method on mglDataC: voidSetAmpl(HCDT ampl, const mglDataA &phase)
-
C function: voidmgl_datac_set_ri(HADT dat, HCDT re, HCDT im)
-
C function: voidmgl_datac_set_ap(HADT dat, HCDT ampl, HCDT phase)
-
Copies the data from mglData instances for real and imaginary parts of complex data arrays.
-
-
-
-
Method on mglData: voidSet(const std::vector<int> &d)
-
Method on mglDataC: voidSet(const std::vector<int> &d)
-
Method on mglData: voidSet(const std::vector<float> &d)
-
Method on mglDataC: voidSet(const std::vector<float> &d)
-
Method on mglData: voidSet(const std::vector<double> &d)
-
Method on mglDataC: voidSet(const std::vector<double> &d)
-
Method on mglDataC: voidSet(const std::vector<dual> &d)
-
Allocates memory and copies the data from the std::vector<T> array.
-
-
-
-
Method on mglData: voidSet(const char *str, int NX, int NY=1, int NZ=1)
-
C function: voidmgl_data_set_values(const char *str, int NX, int NY, int NZ)
-
Method on mglDataC: voidSet(const char *str, int NX, int NY=1, int NZ=1)
-
C function: voidmgl_datac_set_values(const char *str, int NX, int NY, int NZ)
-
Allocates memory and scanf the data from the string.
-
-
-
-
-
Method on mglData: voidSetList(long n, ...)
-
Allocate memory and set data from variable argument list of double values. Note, you need to specify decimal point ‘.’ for integer values! For example, the code SetList(2,0.,1.); is correct, but the code SetList(2,0,1); is incorrect.
-
-
-
-
-
-
Method on mglData: voidLink(mglData &from)
-
Method on mglData: voidLink(mreal *A, int NX, int NY=1, int NZ=1)
-
C function: voidmgl_data_link(HMDT dat, mreal *A, int NX, int NY, int NZ)
-
Method on mglDataC: voidLink(mglDataC &from)
-
Method on mglDataC: voidLink(dual *A, int NX, int NY=1, int NZ=1)
-
C function: voidmgl_datac_link(HADT dat, dual *A, int NX, int NY, int NZ)
-
Links external data array, i.e. don’t delete this array at exit.
-
-
-
-
MGL command: varDAT num v1 [v2=nan]
-
Creates new variable with name dat for one-dimensional array of size num. Array elements are equidistantly distributed in range [v1, v2]. If v2=nan then v2=v1 is used.
-
-
-
-
MGL command: filldat v1 v2 ['dir'='x']
-
Method on mglData: voidFill(mreal v1, mreal v2, char dir='x')
-
Method on mglDataC: voidFill(dual v1, dual v2, char dir='x')
-
C function: voidmgl_data_fill(HMDT dat, mreal v1, mreal v2, char dir)
-
C function: voidmgl_datac_fill(HADT dat, dual v1, dual v2, char dir)
-
Equidistantly fills the data values to range [v1, v2] in direction dir={‘x’,‘y’,‘z’}.
-
Fills the value of array according to the formula in string eq. Formula is an arbitrary expression depending on variables ‘x’, ‘y’, ‘z’, ‘u’, ‘v’, ‘w’. Coordinates ‘x’, ‘y’, ‘z’ are supposed to be normalized in axis range of canvas gr (in difference from Modify functions). Variable ‘u’ is the original value of the array. Variables ‘v’ and ‘w’ are values of vdat, wdat which can be NULL (i.e. can be omitted).
-
-
-
-
MGL command: modifydat 'eq' [dim=0]
-
MGL command: modifydat 'eq' vdat [wdat]
-
Method on mglData: voidModify(const char *eq, int dim=0)
-
Method on mglData: voidModify(const char *eq, const mglDataA &v)
The same as previous ones but coordinates ‘x’, ‘y’, ‘z’ are supposed to be normalized in range [0,1]. If dim>0 is specified then modification will be fulfilled only for slices >=dim.
-
-
-
-
MGL command: fillsampledat 'how'
-
Method on mglData: voidFillSample(const char *how)
-
C function: voidmgl_data_fill_sample(HMDT a, const char *how)
-
Fills data by ’x’ or ’k’ samples for Hankel (’h’) or Fourier (’f’) transform.
-
C function: voidmgl_data_grid(HMGL gr, HMDT u, HCDT x, HCDT y, HCDT z, const char *opt)
-
C function: voidmgl_data_grid_xy(HMDT u, HCDT x, HCDT y, HCDT z, mreal x1, mreal x2, mreal y1, mreal y2)
-
Fills the value of array according to the linear interpolation of triangulated surface assuming x-,y-coordinates equidistantly distributed in axis range (or in range [x1,x2]*[y1,y2]). Triangulated surface is found for arbitrary placed points ‘x’, ‘y’, ‘z’. NAN value is used for grid points placed outside of triangulated surface. See Making regular data, for sample code and picture.
-
-
-
-
-
MGL command: putdat val [i=all j=all k=all]
-
Method on mglData: voidPut(mreal val, int i=-1, int j=-1, int k=-1)
-
Method on mglDataC: voidPut(dual val, int i=-1, int j=-1, int k=-1)
-
C function: voidmgl_data_put_val(HMDT a, mreal val, int i, int j, int k)
-
C function: voidmgl_datac_put_val(HADT a, dual val, int i, int j, int k)
-
Sets value(s) of array a[i, j, k] = val. Negative indexes i, j, k=-1 set the value val to whole range in corresponding direction(s). For example, Put(val,-1,0,-1); sets a[i,0,j]=val for i=0...(nx-1), j=0...(nz-1).
-
-
-
-
MGL command: putdat vdat [i=all j=all k=all]
-
Method on mglData: voidPut(const mglDataA &v, int i=-1, int j=-1, int k=-1)
-
Method on mglDataC: voidPut(const mglDataA &v, int i=-1, int j=-1, int k=-1)
-
C function: voidmgl_data_put_dat(HMDT a, HCDT v, int i, int j, int k)
-
C function: voidmgl_datac_put_dat(HADT a, HCDT v, int i, int j, int k)
-
Copies value(s) from array v to the range of original array. Negative indexes i, j, k=-1 set the range in corresponding direction(s). At this minor dimensions of array v should be large than corresponding dimensions of this array. For example, Put(v,-1,0,-1); sets a[i,0,j]=v.ny>nz ? v[i,j] : v[i], where i=0...(nx-1), j=0...(nz-1) and condition v.nx>=nx is true.
-
-
-
-
MGL command: refilldat xdat vdat [sl=-1]
-
MGL command: refilldat xdat ydat vdat [sl=-1]
-
MGL command: refilldat xdat ydat zdat vdat
-
Method on mglData: voidRefill(const mglDataA &x, const mglDataA &v, mreal x1, mreal x2, long sl=-1)
-
Method on mglData: voidRefill(const mglDataA &x, const mglDataA &v, mglPoint p1, mglPoint p2, long sl=-1)
-
Method on mglData: voidRefill(const mglDataA &x, const mglDataA &y, const mglDataA &v, mglPoint p1, mglPoint p2, long sl=-1)
C function: voidmgl_data_refill_x(HMDT a, HCDT x, HCDT v, mreal x1, mreal x2, long sl)
-
C function: voidmgl_data_refill_xy(HMDT a, HCDT x, HCDT y, HCDT v, mreal x1, mreal x2, mreal y1, mreal y2, long sl)
-
C function: voidmgl_data_refill_xyz(HMDT a, HCDT x, HCDT y, HCDT z, HCDT v, mreal x1, mreal x2, mreal y1, mreal y2, mreal z1, mreal z2)
-
C function: voidmgl_data_refill_gr(HMGL gr, HMDT a, HCDT x, HCDT y, HCDT z, HCDT v, long sl, const char *opt)
-
Fills by interpolated values of array v at the point {x, y, z}={X[i], Y[j], Z[k]} (or {x, y, z}={X[i,j,k], Y[i,j,k], Z[i,j,k]} if x, y, z are not 1d arrays), where X,Y,Z are equidistantly distributed in range [x1,x2]*[y1,y2]*[z1,z2] and have the same sizes as this array. If parameter sl is 0 or positive then changes will be applied only for slice sl.
-
-
-
-
MGL command: gsplinedat xdat vdat [sl=-1]
-
Method on mglData: voidRefillGS(const mglDataA &x, const mglDataA &v, mreal x1, mreal x2, long sl=-1)
-
C function: voidmgl_data_refill_gs(HMDT a, HCDT x, HCDT v, mreal x1, mreal x2, long sl)
-
Fills by global cubic spline values of array v at the point x=X[i], where X are equidistantly distributed in range [x1,x2] and have the same sizes as this array. If parameter sl is 0 or positive then changes will be applied only for slice sl.
-
-
-
-
MGL command: idsetdat 'ids'
-
Method on mglData: voidSetColumnId(const char *ids)
-
Method on mglDataC: voidSetColumnId(const char *ids)
-
C function: voidmgl_data_set_id(HMDT a, const char *ids)
-
C function: voidmgl_datac_set_id(HADT a, const char *ids)
-
Sets the symbol ids for data columns. The string should contain one symbol ’a’...’z’ per column. These ids are used in column.
-
Method on mglData: voidReadRange(const char *templ, mreal from, mreal to, mreal step=1, bool as_slice=false)
-
Method on mglDataC: voidReadRange(const char *templ, mreal from, mreal to, mreal step=1, bool as_slice=false)
-
C function: intmgl_data_read_range(HMDT dat, const char *templ, mreal from, mreal to, mreal step, int as_slice)
-
C function: intmgl_datac_read_range(HADT dat, const char *templ, mreal from, mreal to, mreal step, int as_slice)
-
Join data arrays from several text files. The file names are determined by function call sprintf(fname,templ,val);, where val changes from from to to with step step. The data load one-by-one in the same slice if as_slice=false or as slice-by-slice if as_slice=true.
-
-
-
-
MGL command: readallDAT 'templ' [slice=off]
-
Method on mglData: voidReadAll(const char *templ, bool as_slice=false)
-
Method on mglDataC: voidReadAll(const char *templ, bool as_slice=false)
-
C function: intmgl_data_read_all(HMDT dat, const char *templ, int as_slice)
-
C function: intmgl_datac_read_all(HADT dat, const char *templ, int as_slice)
-
Join data arrays from several text files which filenames satisfied the template templ (for example, templ="t_*.dat"). The data load one-by-one in the same slice if as_slice=false or as slice-by-slice if as_slice=true.
-
-
-
-
MGL command: scanfileDAT 'fname' 'templ'
-
Method on mglData: boolScanFile(const char *fname, const char *templ)
-
C function: intmgl_data_scan_file(HMDT dat, const char *fname, const char *templ)
-
Read file fname line-by-line and scan each line for numbers according the template templ. The numbers denoted as ‘%g’ in the template. See Saving and scanning file, for sample code and picture.
-
-
-
-
MGL command: savedat 'fname'
-
Method on mglDataA: voidSave(const char *fname, int ns=-1) const
-
C function: voidmgl_data_save(HCDT dat, const char *fname, int ns)
-
C function: voidmgl_datac_save(HCDT dat, const char *fname, int ns)
-
Saves the whole data array (for ns=-1) or only ns-th slice to the text file fname.
-
-
-
-
MGL command: save'str' 'fname' ['mode'='a']
-
Saves the string str to the text file fname. For parameter mode=‘a’ will append string to the file (default); for mode=‘w’ will overwrite the file. See Saving and scanning file, for sample code and picture.
-
-
-
-
-
MGL command: readhdfDAT 'fname' 'dname'
-
Method on mglData: voidReadHDF(const char *fname, const char *dname)
-
Method on mglDataC: voidReadHDF(const char *fname, const char *dname)
-
C function: voidmgl_data_read_hdf(HMDT dat, const char *fname, const char *dname)
-
C function: voidmgl_datac_read_hdf(HADT dat, const char *fname, const char *dname)
-
Reads data array named dname from HDF5 or HDF4 file. This function does nothing if HDF5|HDF4 was disabled during library compilation.
-
C function: voidmgl_data_save_hdf(HCDT dat, const char *fname, const char *dname, int rewrite)
-
C function: voidmgl_datac_save_hdf(HCDT dat, const char *fname, const char *dname, int rewrite)
-
Saves data array named dname to HDF5 file. This function does nothing if HDF5 was disabled during library compilation.
-
-
-
-
MGL command: datas'fname'
-
Method on mglDataA: intDatasHDF(const char *fname, char *buf, long size) static
-
C function: intmgl_datas_hdf(const char *fname, char *buf, long size)
-
Put data names from HDF5 file fname into buf as ’\t’ separated fields. In MGL version the list of data names will be printed as message. This function does nothing if HDF5 was disabled during library compilation.
-
-
-
-
MGL command: openhdf'fname'
-
Method on mglParse: voidOpenHDF(const char *fname)
-
C function: voidmgl_parser_openhdf(HMPR pr, const char *fname)
-
Reads all data array from HDF5 file fname and create MGL variables with names of data names in HDF file. Complex variables will be created if data name starts with ‘!’.
-
Reads data from bitmap file (now support only PNG format). The RGB values of bitmap pixels are transformed to mreal values in range [v1, v2] using color scheme scheme (see Color scheme).
-
-
-
-
MGL command: exportdat 'fname' 'sch' [v1=0 v2=0]
-
Method on mglDataA: voidExport(const char *fname, const char *scheme, mreal v1=0, mreal v2=0, int ns=-1) const
-
C function: voidmgl_data_export(HMDT dat, const char *fname, const char *scheme, mreal v1, mreal v2, int ns) const
-
Saves data matrix (or ns-th slice for 3d data) to bitmap file (now support only PNG format). The data values are transformed from range [v1, v2] to RGB pixels of bitmap using color scheme scheme (see Color scheme). If v1>=v2 then the values of v1, v2 are automatically determined as minimal and maximal value of the data array.
-
Method on mglData: mglDataSubData(mreal xx, mreal yy=-1, mreal zz=-1) const
-
Method on mglDataC: mglDataSubData(mreal xx, mreal yy=-1, mreal zz=-1) const
-
C function: HMDTmgl_data_subdata(HCDT dat, mreal xx, mreal yy, mreal zz)
-
Extracts sub-array data from the original data array keeping fixed positive index. For example SubData(-1,2) extracts 3d row (indexes are zero based), SubData(4,-1) extracts 5th column, SubData(-1,-1,3) extracts 4th slice and so on. If argument(s) are non-integer then linear interpolation between slices is used. In MGL version this command usually is used as inline one dat(xx,yy,zz). Function return NULL or create empty data if data cannot be created for given arguments.
-
Method on mglData: mglDataSubData(const mglDataA &xx, const mglDataA &yy) const
-
Method on mglDataC: mglDataSubData(const mglDataA &xx, const mglDataA &yy) const
-
Method on mglData: mglDataSubData(const mglDataA &xx) const
-
Method on mglDataC: mglDataSubData(const mglDataA &xx) const
-
C function: HMDTmgl_data_subdata_ext(HCDT dat, HCDT xx, HCDT yy, HCDT zz)
-
C function: HADTmgl_datac_subdata_ext(HCDT dat, HCDT xx, HCDT yy, HCDT zz)
-
Extracts sub-array data from the original data array for indexes specified by arrays xx, yy, zz (indirect access). This function work like previous one for 1D arguments or numbers, and resulting array dimensions are equal dimensions of 1D arrays for corresponding direction. For 2D and 3D arrays in arguments, the resulting array have the same dimensions as input arrays. The dimensions of all argument must be the same (or to be scalar 1*1*1) if they are 2D or 3D arrays. In MGL version this command usually is used as inline one dat(xx,yy,zz). Function return NULL or create empty data if data cannot be created for given arguments. In C function some of xx, yy, zz can be NULL.
-
-
-
-
MGL command: columnRES dat 'eq'
-
Method on mglData: mglDataColumn(const char *eq) const
-
Method on mglDataC: mglDataColumn(const char *eq) const
-
C function: HMDTmgl_data_column(HCDT dat, const char *eq)
-
Get column (or slice) of the data filled by formula eq on column ids. For example, Column("n*w^2/exp(t)");. The column ids must be defined first by idset function or read from files. In MGL version this command usually is used as inline one dat('eq'). Function return NULL or create empty data if data cannot be created for given arguments.
-
-
-
-
MGL command: resizeRES dat mx [my=1 mz=1]
-
Method on mglData: mglDataResize(int mx, int my=0, int mz=0, mreal x1=0, mreal x2=1, mreal y1=0, mreal y2=1, mreal z1=0, mreal z2=1) const
-
Method on mglDataC: mglDataResize(int mx, int my=0, int mz=0, mreal x1=0, mreal x2=1, mreal y1=0, mreal y2=1, mreal z1=0, mreal z2=1) const
-
C function: HMDTmgl_data_resize(HCDT dat, int mx, int my, int mz)
-
C function: HMDTmgl_data_resize_box(HCDT dat, int mx, int my, int mz, mreal x1, mreal x2, mreal y1, mreal y2, mreal z1, mreal z2)
-
Resizes the data to new size mx, my, mz from box (part) [x1,x2] x [y1,y2] x [z1,z2] of original array. Initially x,y,z coordinates are supposed to be in [0,1]. If one of sizes mx, my or mz is 0 then initial size is used. Function return NULL or create empty data if data cannot be created for given arguments.
-
-
-
-
MGL command: evaluateRES dat idat [norm=on]
-
MGL command: evaluateRES dat idat jdat [norm=on]
-
MGL command: evaluateRES dat idat jdat kdat [norm=on]
-
Method on mglData: mglDataEvaluate(const mglDataA &idat, bool norm=true) const
C function: HMDTmgl_data_evaluate(HCDT dat, HCDT idat, HCDT jdat, HCDT kdat, int norm)
-
Gets array which values is result of interpolation of original array for coordinates from other arrays. All dimensions must be the same for data idat, jdat, kdat. Coordinates from idat, jdat, kdat are supposed to be normalized in range [0,1] (if norm=true) or in ranges [0,nx], [0,ny], [0,nz] correspondingly. Function return NULL or create empty data if data cannot be created for given arguments.
-
-
-
-
MGL command: sectionRES dat ids ['dir'='y' val=nan]
-
MGL command: sectionRES dat id ['dir'='y' val=nan]
C function: HADTmgl_datac_section_val(HCDT dat, long id, const char *dir, mreal val)
-
Gets array which is id-th section (range of slices separated by value val) of original array dat. For id<0 the reverse order is used (i.e. -1 give last section). If several ids are provided then output array will be result of sequential joining of sections.
-
-
-
-
-
MGL command: solveRES dat val 'dir' [norm=on]
-
MGL command: solveRES dat val 'dir' idat [norm=on]
-
Method on mglData: mglDataSolve(mreal val, char dir, bool norm=true) const
C function: HMDTmgl_data_solve(HCDT dat, mreal val, char dir, HCDT idat, int norm)
-
Gets array which values is indexes (roots) along given direction dir, where interpolated values of data dat are equal to val. Output data will have the sizes of dat in directions transverse to dir. If data idat is provided then its values are used as starting points. This allows to find several branches by consequentive calls. Indexes are supposed to be normalized in range [0,1] (if norm=true) or in ranges [0,nx], [0,ny], [0,nz] correspondingly. Function return NULL or create empty data if data cannot be created for given arguments. See Solve sample, for sample code and picture.
-
-
-
-
MGL command: rootsRES 'func' ini ['var'='x']
-
MGL command: rootsRES 'func' ini ['var'='x']
-
Method on mglData: mglDataRoots(const char *func, char var) const
-
C function: HMDTmgl_data_roots(const char *func, HCDT ini, char var)
-
C function: mrealmgl_find_root_txt(const char *func, mreal ini, char var)
-
Find roots of equation ’func’=0 for variable var with initial guess ini. Secant method is used for root finding. Function return NULL or create empty data if data cannot be created for given arguments.
-
-
-
-
MGL command: rootsRES 'funcs' 'vars' ini
-
Method on mglData: mglDataMultiRoots(const char *funcs, const char *vars) const
-
Method on mglDataC: mglDataCMultiRoots(const char *funcs, const char *vars) const
-
C function: HMDTmgl_find_roots_txt(const char *func, const char *vars, HCDT ini)
-
C function: HADTmgl_find_roots_txt_c(const char *func, const char *vars, HCDT ini)
-
Find roots of system of equations ’funcs’=0 for variables vars with initial guesses ini. Secant method is used for root finding. Function return NULL or create empty data if data cannot be created for given arguments.
-
Get curves {x,y}, separated by NAN values, for local maximal values of array dat as function of x-coordinate. Noises below lvl amplitude are ignored. Parameter dj (in range [0,ny]) set the "attraction" y-distance of points to the curve. Similarly, di continue curve in x-direction through gaps smaller than di points. Curves with minimal length smaller than minlen will be ignored.
-
-
-
-
MGL command: histRES dat num v1 v2 [nsub=0]
-
MGL command: histRES dat wdat num v1 v2 [nsub=0]
-
Method on mglData: mglDataHist(int n, mreal v1=0, mreal v2=1, int nsub=0) const
-
Method on mglData: mglDataHist(const mglDataA &w, int n, mreal v1=0, mreal v2=1, int nsub=0) const
-
Method on mglDataC: mglDataHist(int n, mreal v1=0, mreal v2=1, int nsub=0) const
-
Method on mglDataC: mglDataHist(const mglDataA &w, int n, mreal v1=0, mreal v2=1, int nsub=0) const
-
C function: HMDTmgl_data_hist(HCDT dat, int n, mreal v1, mreal v2, int nsub)
-
C function: HMDTmgl_data_hist_w(HCDT dat, HCDT w, int n, mreal v1, mreal v2, int nsub)
-
Creates n-th points distribution of the data values in range [v1, v2]. Array w specifies weights of the data elements (by default is 1). Parameter nsub define the number of additional interpolated points (for smoothness of histogram). Function return NULL or create empty data if data cannot be created for given arguments. See also Data manipulation
-
-
-
-
MGL command: momentumRES dat 'how' ['dir'='z']
-
Method on mglData: mglDataMomentum(char dir, const char *how) const
-
Method on mglDataC: mglDataMomentum(char dir, const char *how) const
-
C function: HMDTmgl_data_momentum(HCDT dat, char dir, const char *how)
-
Gets momentum (1d-array) of the data along direction dir. String how contain kind of momentum. The momentum is defined like as
-res_k = \sum_ij how(x_i,y_j,z_k) a_ij/ \sum_ij a_ij
-if dir=‘z’ and so on. Coordinates ‘x’, ‘y’, ‘z’ are data indexes normalized in range [0,1]. Function return NULL or create empty data if data cannot be created for given arguments.
-
-
-
-
MGL command: sumRES dat 'dir'
-
Method on mglData: mglDataSum(const char *dir) const
-
Method on mglDataC: mglDataSum(const char *dir) const
-
C function: HMDTmgl_data_sum(HCDT dat, const char *dir)
-
Gets array which is the result of summation in given direction or direction(s). Function return NULL or create empty data if data cannot be created for given arguments.
-
-
-
-
MGL command: maxRES dat 'dir'
-
Method on mglData: mglDataMax(const char *dir) const
-
Method on mglDataC: mglDataMax(const char *dir) const
-
C function: HMDTmgl_data_max_dir(HCDT dat, const char *dir)
-
Gets array which is the maximal data values in given direction or direction(s). Function return NULL or create empty data if data cannot be created for given arguments.
-
-
-
-
MGL command: minRES dat 'dir'
-
Method on mglData: mglDataMin(const char *dir) const
-
Method on mglDataC: mglDataMin(const char *dir) const
-
C function: HMDTmgl_data_min_dir(HCDT dat, const char *dir)
-
Gets array which is the maximal data values in given direction or direction(s). Function return NULL or create empty data if data cannot be created for given arguments.
-
-
-
-
MGL command: combineRES adat bdat
-
Method on mglData: mglDataCombine(const mglDataA &a) const
-
Method on mglDataC: mglDataCombine(const mglDataA &a) const
-
C function: HMDTmgl_data_combine(HCDT dat, HCDT a)
-
Returns direct multiplication of arrays (like, res[i,j] = this[i]*a[j] and so on). Function return NULL or create empty data if data cannot be created for given arguments.
-
-
-
-
MGL command: traceRES dat
-
Method on mglData: mglDataTrace() const
-
Method on mglDataC: mglDataTrace() const
-
C function: HMDTmgl_data_trace(HCDT dat)
-
Gets array of diagonal elements a[i,i] (for 2D case) or a[i,i,i] (for 3D case) where i=0...nx-1. Function return copy of itself for 1D case. Data array must have dimensions ny,nz >= nx or ny,nz = 1. Function return NULL or create empty data if data cannot be created for given arguments.
-
-
-
-
MGL command: correlRES adat bdat 'dir'
-
Method on mglData: mglDataCorrel(const mglDataA &b, const char *dir) const
-
Method on mglData: mglDataAutoCorrel(const char *dir) const
-
Method on mglDataC: mglDataCCorrel(const mglDataA &b, const char *dir) const
-
Method on mglDataC: mglDataCAutoCorrel(const char *dir) const
-
C function: HMDTmgl_data_correl(HCDT a, HCDT b, const char *dir)
-
C function: HADTmgl_datac_correl(HCDT a, HCDT b, const char *dir)
-
Find correlation between data a (or this in C++) and b along directions dir. Fourier transform is used to find the correlation. So, you may want to use functions swap or norm before plotting it. Function return NULL or create empty data if data cannot be created for given arguments.
-
-
-
-
Method on mglDataC: mglDataReal() const
-
C function: HMDTmgl_datac_real(HCDT dat)
-
Gets array of real parts of the data.
-
-
-
Method on mglDataC: mglDataImag() const
-
C function: HMDTmgl_datac_imag(HCDT dat)
-
Gets array of imaginary parts of the data.
-
-
-
Method on mglDataC: mglDataAbs() const
-
C function: HMDTmgl_datac_abs(HCDT dat)
-
Gets array of absolute values of the data.
-
-
-
Method on mglDataC: mglDataArg() const
-
C function: HMDTmgl_datac_arg(HCDT dat)
-
Gets array of arguments of the data.
-
-
-
-
MGL command: pulseRES dat 'dir'
-
Method on mglData: mglDataPulse(const char *dir) const
-
C function: HMDTmgl_data_pulse(HCDT dat, const char *dir)
-
Find pulse properties along direction dir: pulse maximum (in column 0) and its position (in column 1), pulse width near maximum (in column 3) and by half height (in column 2), energy in first pulse (in column 4). NAN values are used for widths if maximum is located near the edges. Note, that there is uncertainty for complex data. Usually one should use square of absolute value (i.e. |dat[i]|^2) for them. So, MathGL don’t provide this function for complex data arrays. However, C function will work even in this case but use absolute value (i.e. |dat[i]|). Function return NULL or create empty data if data cannot be created for given arguments. See also max, min, momentum, sum. See Pulse properties, for sample code and picture.
-
These functions change the data in some direction like differentiations, integrations and so on. The direction in which the change will applied is specified by the string parameter, which may contain ‘x’, ‘y’ or ‘z’ characters for 1-st, 2-nd and 3-d dimension correspondingly.
-
-
-
MGL command: cumsumdat 'dir'
-
Method on mglData: voidCumSum(const char *dir)
-
Method on mglDataC: voidCumSum(const char *dir)
-
C function: voidmgl_data_cumsum(HMDT dat, const char *dir)
-
C function: voidmgl_datac_cumsum(HADT dat, const char *dir)
-
Cumulative summation of the data in given direction or directions.
-
-
-
-
MGL command: integratedat 'dir'
-
Method on mglData: voidIntegral(const char *dir)
-
Method on mglDataC: voidIntegral(const char *dir)
-
C function: voidmgl_data_integral(HMDT dat, const char *dir)
-
C function: voidmgl_datac_integral(HADT dat, const char *dir)
-
Integrates (like cumulative summation) the data in given direction or directions.
-
-
-
-
MGL command: diffdat 'dir'
-
Method on mglData: voidDiff(const char *dir)
-
Method on mglDataC: voidDiff(const char *dir)
-
C function: voidmgl_data_diff(HMDT dat, const char *dir)
-
C function: voidmgl_datac_diff(HADT dat, const char *dir)
-
Differentiates the data in given direction or directions.
-
-
-
-
MGL command: diffdat xdat ydat [zdat]
-
Method on mglData: voidDiff(const mglDataA &x)
-
Method on mglData: voidDiff(const mglDataA &x, const mglDataA &y)
C function: voidmgl_data_diff_par(HMDT dat, HCDT x, HCDTy, HCDTz)
-
C function: voidmgl_datac_diff_par(HADT dat, HCDT x, HCDTy, HCDTz)
-
Differentiates the data specified parametrically in direction x with y, z=constant. Parametrical differentiation uses the formula (for 2D case): da/dx = (a_j*y_i-a_i*y_j)/(x_j*y_i-x_i*y_j) where a_i=da/di, a_j=da/dj denotes usual differentiation along 1st and 2nd dimensions. The similar formula is used for 3D case. Note, that you may change the order of arguments – for example, if you have 2D data a(i,j) which depend on coordinates {x(i,j), y(i,j)} then usual derivative along ‘x’ will be Diff(x,y); and usual derivative along ‘y’ will be Diff(y,x);.
-
-
-
-
MGL command: diff2dat 'dir'
-
Method on mglData: voidDiff2(const char *dir)
-
Method on mglDataC: voidDiff2(const char *dir)
-
C function: voidmgl_data_diff2(HMDT dat, const char *dir)
-
C function: voidmgl_datac_diff2(HADT dat, const char *dir)
-
Double-differentiates (like Laplace operator) the data in given direction.
-
-
-
-
MGL command: sinfftdat 'dir'
-
Method on mglData: voidSinFFT(const char *dir)
-
C function: voidmgl_data_sinfft(HMDT dat, const char *dir)
C function: voidmgl_datac_fft(HADT dat, const char *dir)
-
Do Fourier transform of the data in given direction or directions. If dir contain ‘i’ then inverse Fourier is used. The Fourier transform is \sum a_j \exp(i k j) (see http://en.wikipedia.org/wiki/Discrete_Fourier_transform).
-
-
-
-
MGL command: hankeldat 'dir'
-
Method on mglData: voidHankel(const char *dir)
-
Method on mglDataC: voidHankel(const char *dir)
-
C function: voidmgl_data_hankel(HMDT dat, const char *dir)
-
C function: voidmgl_datac_hankel(HADT dat, const char *dir)
Method on mglData: voidWavelet(const char *dir, int k)
-
C function: voidmgl_data_wavelet(HMDT dat, const char *dir, int k)
-
Apply wavelet transform of the data in given direction or directions. Parameter dir set the kind of wavelet transform:
-‘d’ for daubechies, ‘D’ for centered daubechies, ‘h’ for haar, ‘H’ for centered haar, ‘b’ for bspline, ‘B’ for centered bspline. If string dir contain symbol ‘i’ then inverse wavelet transform is applied. Parameter k set the size of wavelet transform.
-
-
-
-
MGL command: swapdat 'dir'
-
Method on mglData: voidSwap(const char *dir)
-
Method on mglDataC: voidSwap(const char *dir)
-
C function: voidmgl_data_swap(HMDT dat, const char *dir)
-
C function: voidmgl_datac_swap(HADT dat, const char *dir)
-
Swaps the left and right part of the data in given direction (useful for Fourier spectrum).
-
-
-
-
MGL command: rolldat 'dir' num
-
Method on mglData: voidRoll(char dir, num)
-
Method on mglDataC: voidRoll(char dir, num)
-
C function: voidmgl_data_roll(HMDT dat, char dir, num)
-
C function: voidmgl_datac_roll(HADT dat, char dir, num)
-
Rolls the data along direction dir. Resulting array will be out[i] = ini[(i+num)%nx] if dir='x'.
-
-
-
-
MGL command: mirrordat 'dir'
-
Method on mglData: voidMirror(const char *dir)
-
Method on mglDataC: voidMirror(const char *dir)
-
C function: voidmgl_data_mirror(HMDT dat, const char *dir)
-
C function: voidmgl_datac_mirror(HADT dat, const char *dir)
-
Mirror the left-to-right part of the data in given direction. Looks like change the value index i->n-i. Note, that the similar effect in graphics you can reach by using options (see Command options), for example, surf dat; xrange 1 -1.
-
-
-
-
MGL command: sewdat ['dir'='xyz' da=2*pi]
-
Method on mglData: voidSew(const char *dir, mreal da=2*M_PI)
-
C function: voidmgl_data_sew(HMDT dat, const char *dir, mreal da)
-
Remove value steps (like phase jumps after inverse trigonometric functions) with period da in given direction.
-
-
-
-
MGL command: smoothdata ['dir'='xyz']
-
Method on mglData: voidSmooth(const char *dir="xyz", mreal delta=0)
-
Method on mglDataC: voidSmooth(const char *dir="xyz", mreal delta=0)
-
C function: voidmgl_data_smooth(HMDT dat, const char *dir, mreal delta)
-
C function: voidmgl_datac_smooth(HADT dat, const char *dir, mreal delta)
-
Smooths the data on specified direction or directions. String dirs specifies the dimensions which will be smoothed. It may contain characters:
-
-
‘xyz’ for smoothing along x-,y-,z-directions correspondingly,
-
‘0’ does nothing,
-
‘3’ for linear averaging over 3 points,
-
‘5’ for linear averaging over 5 points,
-
‘d1’...‘d9’ for linear averaging over (2*N+1)-th points,
-
‘^’ for finding upper bound,
-
‘_’ for finding lower bound.
-
-
By default quadratic averaging over 5 points is used.
-
-
-
-
MGL command: envelopdat ['dir'='x']
-
Method on mglData: voidEnvelop(char dir='x')
-
C function: voidmgl_data_envelop(HMDT dat, char dir)
-
Find envelop for data values along direction dir.
-
-
-
-
MGL command: diffractdat 'how' q
-
Method on mglDataC: voidDiffraction(const char *how, mreal q)
-
C function: voidmgl_datac_diffr(HADT dat, const char *how, mreal q)
-
Calculates one step of diffraction by finite-difference method with parameter q=\delta t/\delta x^2 using method with 3-d order of accuracy. Parameter how may contain:
-
-
‘xyz’ for calculations along x-,y-,z-directions correspondingly;
-
‘r’ for using axial symmetric Laplace operator for x-direction;
-
‘0’ for zero boundary conditions;
-
‘1’ for constant boundary conditions;
-
‘2’ for linear boundary conditions;
-
‘3’ for parabolic boundary conditions;
-
‘4’ for exponential boundary conditions;
-
‘5’ for gaussian boundary conditions.
-
-
-
-
-
MGL command: normdat v1 v2 [sym=off dim=0]
-
Method on mglData: voidNorm(mreal v1=0, mreal v2=1, bool sym=false, long dim=0)
-
C function: voidmgl_data_norm(HMDT dat, mreal v1, mreal v2, int sym, long dim)
-
Normalizes the data to range [v1,v2]. If flag sym=true then symmetrical interval [-max(|v1|,|v2|), max(|v1|,|v2|)] is used. Modification will be applied only for slices >=dim.
-
C function: voidmgl_data_norm_slice(HMDT dat, mreal v1, mreal v2, char dir, int keep, int sym)
-
Normalizes data slice-by-slice along direction dir the data in slices to range [v1,v2]. If flag sym=true then symmetrical interval [-max(|v1|,|v2|), max(|v1|,|v2|)] is used. If keep is set then maximal value of k-th slice will be limited by
-\sqrt{\sum a_ij(k)/\sum a_ij(0)}.
-
-
-
-
MGL command: limitdat val
-
Method on mglData: voidLimit(mreal val)
-
Method on mglDataC: voidLimit(mreal val)
-
C function: voidmgl_data_limit(HMDT dat, mreal val)
-
C function: voidmgl_datac_limit(HADT dat, mreal val)
-
Limits the data values to be inside the range [-val,val], keeping the original sign of the value (phase for complex numbers). This is equivalent to operation a[i] *= abs(a[i])<val?1.:val/abs(a[i]);.
-
-
-
-
MGL command: coildat v1 v2 [sep=on]
-
Method on mglData: voidCoil(mreal v1, mreal v2, bool sep=true)
-
C function: voidmgl_data_coil(HMDT dat, mreal v1, mreal v2, int sep)
-
Project the periodical data to range [v1,v2] (like mod() function). Separate branches by NAN if sep=true.
-
-
-
-
-
MGL command: dilatedat [val=1 step=1]
-
Method on mglData: voidDilate(mreal val=1, long step=1)
-
C function: voidmgl_data_dilate(HMDT dat, mreal val, long step)
-
Return dilated by step cells array of 0 or 1 for data values larger val.
-
-
-
MGL command: erodedat [val=1 step=1]
-
Method on mglData: voidErode(mreal val=1, long step=1)
-
C function: voidmgl_data_erode(HMDT dat, mreal val, long step)
-
Return eroded by step cells array of 0 or 1 for data values larger val.
C function: mrealmgl_data_spline_ext(HCDT dat, mreal x, mreal y, mreal z, mreal *dx, mreal *dy, mreal *dz)
-
C function: dualmgl_datac_spline_ext(HCDT dat, mreal x, mreal y, mreal z, dual *dx, dual *dy, dual *dz)
-
Interpolates data by cubic spline to the given point x in [0...nx-1], y in [0...ny-1], z in [0...nz-1]. The values of derivatives at the point are saved in dif.
-
Interpolates data by cubic spline to the given point x, y, z which assumed to be normalized in range [0, 1]. The values of derivatives at the point are saved in dif.
-
-
-
-
-
Method on mglData: mrealLinear(mreal x, mreal y=0, mreal z=0) const
-
Method on mglDataC: dualLinear(mreal x, mreal y=0, mreal z=0) const
-
C function: mrealmgl_data_linear(HCDT dat, mreal x, mreal y, mreal z)
-
C function: dualmgl_datac_linear(HCDT dat, mreal x, mreal y, mreal z)
-
Interpolates data by linear function to the given point x in [0...nx-1], y in [0...ny-1], z in [0...nz-1].
-
-
-
-
Method on mglData: mrealLinear1(mreal x, mreal y=0, mreal z=0) const
-
Method on mglDataC: dualLinear1(mreal x, mreal y=0, mreal z=0) const
-
Interpolates data by linear function to the given point x, y, z which assumed to be normalized in range [0, 1].
-
C function: mrealmgl_data_linear_ext(HCDT dat, mreal x, mreal y, mreal z, mreal *dx, mreal *dy, mreal *dz)
-
C function: dualmgl_datac_linear_ext(HCDT dat, mreal x, mreal y, mreal z, dual *dx, dual *dy, dual *dz)
-
Interpolates data by linear function to the given point x in [0...nx-1], y in [0...ny-1], z in [0...nz-1]. The values of derivatives at the point are saved in dif.
-
Interpolates data by linear function to the given point x, y, z which assumed to be normalized in range [0, 1]. The values of derivatives at the point are saved in dif.
-
There are a set of functions for obtaining data properties in MGL language. However most of them can be found using "suffixes". Suffix can get some numerical value of the data array (like its size, maximal or minimal value, the sum of elements and so on) as number. Later it can be used as usual number in command arguments. The suffixes start from point ‘.’ right after (without spaces) variable name or its sub-array. For example, a.nx give the x-size of data a, b(1).max give maximal value of second row of variable b, (c(:,0)^2).sum give the sum of squares of elements in the first column of c and so on.
-
-
-
-
-
MGL command: infodat
-
Method on mglDataA: const char *PrintInfo() const
-
Method on mglDataA: voidPrintInfo(FILE *fp) const
-
C function only: const char *mgl_data_info(HCDT dat)
-
Fortran subroutine: mgl_data_info(long dat, char *out, int len)
-
Gets or prints to file fp or as message (in MGL) information about the data (sizes, maximum/minimum, momentums and so on).
-
-
-
-
MGL command: info'txt'
-
Prints string txt as message.
-
-
-
-
MGL command: infoval
-
Prints value of number val as message.
-
-
-
-
MGL command: printdat
-
MGL command: print'txt'
-
MGL command: printval
-
The same as info but immediately print to stdout.
-
-
-
-
MGL command: echodat
-
Prints all values of the data array dat as message.
-
-
-
-
MGL command: progressval max
-
Method on mglGraph: voidProgress(int val, int max)
-
C function: voidmgl_progress(int val, int max)
-
Display progress of something as filled horizontal bar with relative length val/max. Note, it work now only in console and in FLTK-based applications, including mgllab and mglview.
-
-
-
-
-
-
-
-
MGL suffix: (dat).nx
-
MGL suffix: (dat).ny
-
MGL suffix: (dat).nz
-
Method on mglDataA: longGetNx()
-
Method on mglDataA: longGetNy()
-
Method on mglDataA: longGetNz()
-
C function: longmgl_data_get_nx(HCDT dat)
-
C function: longmgl_data_get_ny(HCDT dat)
-
C function: longmgl_data_get_nz(HCDT dat)
-
Gets the x-, y-, z-size of the data.
-
-
-
-
-
-
-
MGL suffix: (dat).max
-
Method on mglDataA: mrealMaximal() const
-
C function: mrealmgl_data_max(HCDT dat)
-
Gets maximal value of the data.
-
-
-
-
-
MGL suffix: (dat).min
-
Method on mglDataA: mrealMinimal() const
-
C function: mrealmgl_data_min(HMDT dat) const
-
Gets minimal value of the data.
-
-
-
-
Method on mglDataA: mrealMinimal(int &i, int &j, int &k) const
-
C function: mrealmgl_data_min_int(HCDT dat, int *i, int *j, int *k)
-
Gets position of minimum to variables i, j, k and returns the minimal value.
-
-
-
Method on mglDataA: mrealMaximal(int &i, int &j, int &k) const
-
C function: mrealmgl_data_max_int(HCDT dat, int *i, int *j, int *k)
-
Gets position of maximum to variables i, j, k and returns the maximal value.
-
-
-
Method on mglDataA: mrealMinimal(mreal &x, mreal &y, mreal &z) const
-
C function: mrealmgl_data_min_real(HCDT dat, mreal *x, mreal *y, mreal *z)
-
Gets approximated (interpolated) position of minimum to variables x, y, z and returns the minimal value.
-
-
-
-
MGL suffix: (dat).mx
-
MGL suffix: (dat).my
-
MGL suffix: (dat).mz
-
Method on mglDataA: mrealMaximal(mreal &x, mreal &y, mreal &z) const
-
C function: mrealmgl_data_max_real(HCDT dat, mreal *x, mreal *y, mreal *z)
-
Gets approximated (interpolated) position of maximum to variables x, y, z and returns the maximal value.
-
-
-
-
-
MGL suffix: (dat).mxf
-
MGL suffix: (dat).myf
-
MGL suffix: (dat).mzf
-
MGL suffix: (dat).mxl
-
MGL suffix: (dat).myl
-
MGL suffix: (dat).mzl
-
Method on mglDataA: longMaximal(char dir, long from) const
-
Method on mglDataA: longMaximal(char dir, long from, long &p1, long &p2) const
-
C function: mrealmgl_data_max_firstl(HCDT dat, char dir, long from, long *p1, long *p2)
-
Get first starting from give position (or last one if from<0) maximum along direction dir, and save its orthogonal coordinates in p1, p2.
-
-
-
-
-
-
MGL suffix: (dat).sum
-
MGL suffix: (dat).ax
-
MGL suffix: (dat).ay
-
MGL suffix: (dat).az
-
MGL suffix: (dat).aa
-
MGL suffix: (dat).wx
-
MGL suffix: (dat).wy
-
MGL suffix: (dat).wz
-
MGL suffix: (dat).wa
-
MGL suffix: (dat).sx
-
MGL suffix: (dat).sy
-
MGL suffix: (dat).sz
-
MGL suffix: (dat).sa
-
MGL suffix: (dat).kx
-
MGL suffix: (dat).ky
-
MGL suffix: (dat).kz
-
MGL suffix: (dat).ka
-
Method on mglDataA: mrealMomentum(char dir, mreal &a, mreal &w) const
Gets zero-momentum (energy, I=\sum dat_i) and write first momentum (median, a = \sum \xi_i dat_i/I), second momentum (width, w^2 = \sum (\xi_i-a)^2 dat_i/I), third momentum (skewness, s = \sum (\xi_i-a)^3 dat_i/ I w^3) and fourth momentum (kurtosis, k = \sum (\xi_i-a)^4 dat_i / 3 I w^4) to variables. Here \xi is corresponding coordinate if dir is ‘'x'’, ‘'y'’ or ‘'z'’. Otherwise median is a = \sum dat_i/N, width is w^2 = \sum (dat_i-a)^2/N and so on.
-
-
-
-
MGL suffix: (dat).fst
-
-
Method on mglDataA: mrealFind(const char *cond, int &i, int &j, int &k) const
-
C function: mrealmgl_data_first(HCDT dat, const char *cond, int *i, int *j, int *k)
-
Find position (after specified in i, j, k) of first nonzero value of formula cond. Function return the data value at found position.
-
-
-
-
MGL suffix: (dat).lst
-
-
Method on mglDataA: mrealLast(const char *cond, int &i, int &j, int &k) const
-
C function: mrealmgl_data_last(HCDT dat, const char *cond, int *i, int *j, int *k)
-
Find position (before specified in i, j, k) of last nonzero value of formula cond. Function return the data value at found position.
-
-
-
-
Method on mglDataA: intFind(const char *cond, char dir, int i=0, int j=0, int k=0) const
-
C function: mrealmgl_data_find(HCDT dat, const char *cond, int i, int j, int k)
-
Return position of first in direction dir nonzero value of formula cond. The search is started from point {i,j,k}.
-
-
-
-
Method on mglDataA: boolFindAny(const char *cond) const
-
C function: mrealmgl_data_find_any(HCDT dat, const char *cond)
-
Determines if any nonzero value of formula in the data array.
-
C function: HMDTmgl_transform(HCDT real, HCDT imag, const char *type)
-
Does integral transformation of complex data real, imag on specified direction. The order of transformations is specified in string type: first character for x-dimension, second one for y-dimension, third one for z-dimension. The possible character are: ‘f’ is forward Fourier transformation, ‘i’ is inverse Fourier transformation, ‘s’ is Sine transform, ‘c’ is Cosine transform, ‘h’ is Hankel transform, ‘n’ or ‘’ is no transformation.
-
C function: voidmgl_data_fourierHCDT re, HCDT im, const char *dir)
-
C function: voidmgl_datac_fft(HADT dat, const char *dir)
-
Does Fourier transform of complex data re+i*im in directions dir. Result is placed back into re and im data arrays. If dir contain ‘i’ then inverse Fourier is used.
-
-
-
-
MGL command: stfadRES real imag dn ['dir'='x']
-
Global function: mglDatamglSTFA(const mglDataA &real, const mglDataA &imag, int dn, char dir='x')
-
C function: HMDTmgl_data_stfa(HCDT real, HCDT imag, int dn, char dir)
-
Short time Fourier transformation for real and imaginary parts. Output is amplitude of partial Fourier of length dn. For example if dir=‘x’, result will have size {int(nx/dn), dn, ny} and it will contain res[i,j,k]=|\sum_d^dn exp(I*j*d)*(real[i*dn+d,k]+I*imag[i*dn+d,k])|/dn.
-
-
-
-
MGL command: triangulatedat xdat ydat
-
Global function: mglDatamglTriangulation(const mglDataA &x, const mglDataA &y)
-
C function: voidmgl_triangulation_2d(HCDT x, HCDT y)
-
Do Delone triangulation for 2d points and return result suitable for triplot and tricont. See Making regular data, for sample code and picture.
-
C function: HMDTmgl_data_tridmat(HCDT A, HCDT B, HCDT C, HCDT D, const char*how)
-
C function: HADTmgl_datac_tridmat(HCDT A, HCDT B, HCDT C, HCDT D, const char*how)
-
Get array as solution of tridiagonal system of equations A[i]*x[i-1]+B[i]*x[i]+C[i]*x[i+1]=D[i]. String how may contain:
-
-
‘xyz’ for solving along x-,y-,z-directions correspondingly;
-
‘h’ for solving along hexagonal direction at x-y plain (require square matrix);
-
‘c’ for using periodical boundary conditions;
-
‘d’ for for diffraction/diffuse calculation (i.e. for using -A[i]*D[i-1]+(2-B[i])*D[i]-C[i]*D[i+1] at right part instead of D[i]).
-
-
Data dimensions of arrays A, B, C should be equal. Also their dimensions need to be equal to all or to minor dimension(s) of array D. See PDE solving hints, for sample code and picture.
-
Solves equation du/dz = i*k0*ham(p,q,x,y,z,|u|)[u], where p=-i/k0*d/dx, q=-i/k0*d/dy are pseudo-differential operators. Parameters ini_re, ini_im specify real and imaginary part of initial field distribution. Parameters Min, Max set the bounding box for the solution. Note, that really this ranges are increased by factor 3/2 for purpose of reducing reflection from boundaries. Parameter dz set the step along evolutionary coordinate z. At this moment, simplified form of function ham is supported – all “mixed” terms (like ‘x*p’->x*d/dx) are excluded. For example, in 2D case this function is effectively ham = f(p,z) + g(x,z,u). However commutable combinations (like ‘x*q’->x*d/dy) are allowed. Here variable ‘u’ is used for field amplitude |u|. This allow one solve nonlinear problems – for example, for nonlinear Shrodinger equation you may set ham="p^2 + q^2 - u^2". You may specify imaginary part for wave absorption, like ham = "p^2 + i*x*(x>0)". See also apde, qo2d, qo3d. See PDE solving hints, for sample code and picture.
-
Solves equation du/dz = i*k0*ham(p,q,x,y,z,|u|)[u], where p=-i/k0*d/dx, q=-i/k0*d/dy are pseudo-differential operators. Parameters ini_re, ini_im specify real and imaginary part of initial field distribution. Parameters Min, Max set the bounding box for the solution. Note, that really this ranges are increased by factor 3/2 for purpose of reducing reflection from boundaries. Parameter dz set the step along evolutionary coordinate z. The advanced and rather slow algorithm is used for taking into account both spatial dispersion and inhomogeneities of media [see A.A. Balakin, E.D. Gospodchikov, A.G. Shalashov, JETP letters v.104, p.690-695 (2016)]. Variable ‘u’ is used for field amplitude |u|. This allow one solve nonlinear problems – for example, for nonlinear Shrodinger equation you may set ham="p^2 + q^2 - u^2". You may specify imaginary part for wave absorption, like ham = "p^2 + i*x*(x>0)". See also pde. See PDE solving hints, for sample code and picture.
-
Solves GO ray equation like dr/dt = d ham/dp, dp/dt = -d ham/dr. This is Hamiltonian equations for particle trajectory in 3D case. Here ham is Hamiltonian which may depend on coordinates ‘x’, ‘y’, ‘z’, momentums ‘p’=px, ‘q’=py, ‘v’=pz and time ‘t’: ham = H(x,y,z,p,q,v,t). The starting point (at t=0) is defined by variables r0, p0. Parameters dt and tmax specify the integration step and maximal time for ray tracing. Result is array of {x,y,z,p,q,v,t} with dimensions {7 * int(tmax/dt+1) }.
-
-
-
-
MGL command: odeRES 'df' 'var' ini [dt=0.1 tmax=10]
C function: HMDTmgl_ode_solve_str(const char *df, const char *var, HCDT ini, mreal dt, mreal tmax)
-
C function: HADTmgl_ode_solve_str_c(const char *df, const char *var, HCDT ini, mreal dt, mreal tmax)
-
C function: HMDTmgl_ode_solve(void (*df)(const mreal *x, mreal *dx, void *par), int n, const mreal *ini, mreal dt, mreal tmax)
-
C function: HMDTmgl_ode_solve_ex(void (*df)(const mreal *x, mreal *dx, void *par), int n, const mreal *ini, mreal dt, mreal tmax, void (*bord)(mreal *x, const mreal *xprev, void *par))
-
Solves ODE equations dx/dt = df(x). The functions df can be specified as string of ’;’-separated textual formulas (argument var set the character ids of variables x[i]) or as callback function, which fill dx array for give x’s. Parameters ini, dt, tmax set initial values, time step and maximal time of the calculation. Function stop execution if NAN or INF values appears. Result is data array with dimensions {n * Nt}, where Nt <= int(tmax/dt+1)
-
-
-
-
MGL command: qo2dRES 'ham' ini_re ini_im ray [r=1 k0=100 xx yy]
C function: HMDTmgl_qo2d_func(dual (*ham)(mreal u, mreal x, mreal y, mreal px, mreal py, void *par), HCDT ini_re, HCDT ini_im, HCDT ray, mreal r, mreal k0, HMDT xx, HMDT yy)
-
C function: HADTmgl_qo2d_func_c(dual (*ham)(mreal u, mreal x, mreal y, mreal px, mreal py, void *par), HCDT ini_re, HCDT ini_im, HCDT ray, mreal r, mreal k0, HMDT xx, HMDT yy)
-
Solves equation du/dt = i*k0*ham(p,q,x,y,|u|)[u], where p=-i/k0*d/dx, q=-i/k0*d/dy are pseudo-differential operators (see mglPDE() for details). Parameters ini_re, ini_im specify real and imaginary part of initial field distribution. Parameters ray set the reference ray, i.e. the ray around which the accompanied coordinate system will be maked. You may use, for example, the array created by ray function. Note, that the reference ray must be smooth enough to make accompanied coodrinates unambiguity. Otherwise errors in the solution may appear. If xx and yy are non-zero then Cartesian coordinates for each point will be written into them. See also pde, qo3d. See PDE solving hints, for sample code and picture.
-
-
-
-
-
MGL command: qo3dRES 'ham' ini_re ini_im ray [r=1 k0=100 xx yy zz]
Solves equation du/dt = i*k0*ham(p,q,v,x,y,z,|u|)[u], where p=-i/k0*d/dx, q=-i/k0*d/dy, v=-i/k0*d/dz are pseudo-differential operators (see mglPDE() for details). Parameters ini_re, ini_im specify real and imaginary part of initial field distribution. Parameters ray set the reference ray, i.e. the ray around which the accompanied coordinate system will be maked. You may use, for example, the array created by ray function. Note, that the reference ray must be smooth enough to make accompanied coodrinates unambiguity. Otherwise errors in the solution may appear. If xx and yy and zz are non-zero then Cartesian coordinates for each point will be written into them. See also pde, qo2d. See PDE solving hints, for sample code and picture.
-
-
-
-
-
MGL command: jacobianRES xdat ydat [zdat]
-
Global function: mglDatamglJacobian(const mglDataA &x, const mglDataA &y)
C function: HMDTmgl_jacobian_3d(HCDT x, HCDT y, HCDT z)
-
Computes the Jacobian for transformation {i,j,k} to {x,y,z} where initial coordinates {i,j,k} are data indexes normalized in range [0,1]. The Jacobian is determined by formula det||dr_\alpha/d\xi_\beta|| where r={x,y,z} and \xi={i,j,k}. All dimensions must be the same for all data arrays. Data must be 3D if all 3 arrays {x,y,z} are specified or 2D if only 2 arrays {x,y} are specified.
-
-
-
-
MGL command: triangulationRES xdat ydat
-
Global function: mglDatamglTriangulation(const mglDataA &x, const mglDataA &y)
-
C function: HMDTmgl_triangulation_2d(HCDT x, HCDT y)
-
Computes triangulation for arbitrary placed points with coordinates {x,y} (i.e. finds triangles which connect points). MathGL use s-hull code for triangulation. The sizes of 1st dimension must be equal for all arrays x.nx=y.nx. Resulting array can be used in triplot or tricont functions for visualization of reconstructed surface. See Making regular data, for sample code and picture.
-
-
-
-
-
Global function: mglDatamglGSplineInit(const mglDataA &x, const mglDataA &y)
-
Global function: mglDataCmglGSplineCInit(const mglDataA &x, const mglDataA &y)
-
C function: HMDTmgl_gspline_init(HCDT x, HCDT y)
-
C function: HADTmgl_gsplinec_init(HCDT x, HCDT y)
-
Prepare coefficients for global cubic spline interpolation.
-
C function: mrealmgl_gspline(HCDT coef, mreal dx, mreal *d1, mreal *d2)
-
C function: dualmgl_gsplinec(HCDT coef, mreal dx, dual *d1, dual *d2)
-
Evaluate global cubic spline (and its 1st and 2nd derivatives d1, d2 if they are not NULL) using prepared coefficients coef at point dx+x0 (where x0 is 1st element of data x provided to mglGSpline*Init() function).
-
-
-
-
-
-
MGL command: ifs2dRES dat num [skip=20]
-
Global function: mglDatamglIFS2d(const mglDataA &dat, long num, long skip=20)
-
C function: HMDTmgl_data_ifs_2d(HCDT dat, long num, long skip)
-
Computes num points {x[i]=res[0,i], y[i]=res[1,i]} for fractal using iterated function system. Matrix dat is used for generation according the formulas
-
Value dat[6,i] is used as weight factor for i-th row of matrix dat. At this first skip iterations will be omitted. Data array dat must have x-size greater or equal to 7. See also ifs3d, flame2d. See ifs2d sample, for sample code and picture.
-
-
-
-
MGL command: ifs3dRES dat num [skip=20]
-
Global function: mglDatamglIFS3d(const mglDataA &dat, long num, long skip=20)
-
C function: HMDTmgl_data_ifs_3d(HCDT dat, long num, long skip)
-
Computes num points {x[i]=res[0,i], y[i]=res[1,i], z[i]=res[2,i]} for fractal using iterated function system. Matrix dat is used for generation according the formulas
-
Value dat[12,i] is used as weight factor for i-th row of matrix dat. At this first skip iterations will be omitted. Data array dat must have x-size greater or equal to 13. See also ifs2d. See ifs3d sample, for sample code and picture.
-
-
-
-
MGL command: ifsfileRES 'fname' 'name' num [skip=20]
-
Global function: mglDatamglIFSfile(const char *fname, const char *name, long num, long skip=20)
-
C function: HMDTmgl_data_ifs_file(const char *fname, const char *name, long num, long skip)
-
Reads parameters of IFS fractal named name from file fname and computes num points for this fractal. At this first skip iterations will be omitted. See also ifs2d, ifs3d.
-
-
IFS file may contain several records. Each record contain the name of fractal (‘binary’ in the example below) and the body of fractal, which is enclosed in curly braces {}. Symbol ‘;’ start the comment. If the name of fractal contain ‘(3D)’ or ‘(3d)’ then the 3d IFS fractal is specified. The sample below contain two fractals: ‘binary’ – usual 2d fractal, and ‘3dfern (3D)’ – 3d fractal. See also ifs2d, ifs3d.
-
Global function: mglDatamglFlame2d(const mglDataA &dat, const mglDataA &func, long num, long skip=20)
-
C function: HMDTmgl_data_flame_2d(HCDT dat, HCDT func, long num, long skip)
-
Computes num points {x[i]=res[0,i], y[i]=res[1,i]} for "flame" fractal using iterated function system. Array func define "flame" function identificator (func[0,i,j]), its weight (func[0,i,j]) and arguments (func[2 ... 5,i,j]). Matrix dat set linear transformation of coordinates before applying the function. The resulting coordinates are
-
MathGL have a special classes mglExpr and mglExprC for evaluating of formula specified by the string for real and complex numbers correspondingly. These classes are defined in #include <mgl2/data.h> and #include <mgl2/datac.h> correspondingly. It is the fast variant of formula evaluation. At creation it will be recognized and compiled to tree-like internal code. At evaluation stage only fast calculations are performed. There is no difference between lower or upper case in formulas. If argument value lie outside the range of function definition then function returns NaN. See Textual formulas.
-
-
-
Constructor on mglExpr: mglExpr(const char *expr)
-
Constructor on mglExprC: mglExprC(const char *expr)
-
C function: HMEXmgl_create_expr(const char *expr)
-
C function: HAEXmgl_create_cexpr(const char *expr)
-
Parses the formula expr and creates formula-tree. Constructor recursively parses the formula and creates a tree-like structure containing functions and operators for fast further evaluating by Calc() or CalcD() functions.
-
-
-
-
Destructor on mglExpr: ~mglExpr()
-
Destructor on mglExprC: ~mglExprC()
-
C function: voidmgl_delete_expr(HMEX ex)
-
C function: voidmgl_delete_cexpr(HAEX ex)
-
Deletes the instance of class mglExpr.
-
-
-
-
Method on mglExpr: mrealEval(mreal x, mreal y, mreal z)
-
Method on mglExprC: dualEval(dual x, dual y, dual z)
-
C function: mrealmgl_expr_eval(HMEX ex, mreal x, mreal y, mreal z)
-
C function: dualmgl_cexpr_eval(HAEX ex, dual x, dual y, dual z)
-
Evaluates the formula for 'x','r'=x, 'y','n'=y, 'z','t'=z, 'a','u'=u.
-
-
-
-
Method on mglExpr: mrealEval(mreal var[26])
-
Method on mglExprC: dualEval(dual var[26])
-
C function: mrealmgl_expr_eval_v(HMEX ex, mreal *var)
-
C function: dualmgl_expr_eval_v(HAEX ex, dual *var)
-
Evaluates the formula for variables in array var[0,...,’z’-’a’].
-
-
-
-
-
Method on mglExpr: mrealDiff(char dir, mreal x, mreal y, mreal z)
-
C function: mrealmgl_expr_diff(HMEX ex, char dir, mreal x, mreal y, mreal z)
-
Evaluates the formula derivation respect to dir for 'x','r'=x, 'y','n'=y, 'z','t'=z, 'a','u'=u.
-
-
-
-
Method on mglExpr: mrealDiff(char dir, mreal var[26])
-
C function: mrealmgl_expr_diff_v(HMEX ex, char dir, mreal *var)
-
Evaluates the formula derivation respect to dir for variables in array var[0,...,’z’-’a’].
-
This section describe special data classes mglDataV, mglDataF, mglDataT and mglDataR which sometime can noticeable speed up drawing or data handling. These classes are defined in #include <mgl2/data.h>. Note, that all plotting and data handling routines can be done using usual mglData or mglDataC classes. Also these special classes are usable in C++ code only.
-
-
-
Class mglDataV
-
represent variable with values equidistantly distributed in given range.
-
-
Constructor on mglDataV: mglDataV(const mglDataV & d)
-
Copy constructor.
-
-
-
Constructor on mglDataV: mglDataV(long nx=1, long ny=1, long nz=1, mreal v1=0, mreal v2=NaN, char dir='x')
-
Create variable with "sizes" nxxnyxnz which changes from v1 to v2 (or is constant if v2=NaN) along dir direction.
-
-
-
Method on mglDataV: voidCreate(long nx=1, long ny=1, long nz=1)
-
Set "sizes" nxxnyxnz.
-
-
-
Method on mglDataV: voidFill(mreal x1, mreal x2=NaN, char dir='x')
-
Set ranges of the variable.
-
-
-
Method on mglDataV: voidFreq(mreal dp, char dir='x')
-
Set as frequency variable with increment dp.
-
-
-
-
Class mglDataF
-
represent function which values are evaluated (instead of access to data array as in mglData).
-
-
Constructor on mglDataF: mglDataF(const mglDataF & d)
-
Copy constructor.
-
-
-
Constructor on mglDataF: mglDataF(long nx=1, long ny=1, long nz=1)
-
Create variable with "sizes" nxxnyxnz with zero function.
-
-
-
Method on mglDataF: voidCreate(long nx=1, long ny=1, long nz=1)
-
Set "sizes" nxxnyxnz.
-
-
-
Method on mglDataF: voidSetRanges(mglPoint p1, mglPoint p2)
-
Set ranges for internal x,y,z variables.
-
-
-
Method on mglDataF: voidSetFormula(const char *func)
-
Set string which will be evaluated at function calls. Note this variant is about 10 times slower than SetFunc() one.
-
MathGL library supports the simplest scripts for data handling and plotting. These scripts can be used independently (with the help of UDAV, mglconv, mglview programs and others
-, see Utilities) or in the frame of the library using.
-
MGL script language is rather simple. Each string is a command. First word of string is the name of command. Other words are command arguments. Words are separated from each other by space or tabulation symbol. The upper or lower case of words is important, i.e. variables a and A are different variables. Symbol ‘#’ starts the comment (all characters after # will be ignored). The exception is situation when ‘#’ is a part of some string. Also options can be specified after symbol ‘;’ (see Command options). Symbol ‘:’ starts new command (like new line character) if it is not placed inside a string or inside brackets.
-
-
If string contain references to external parameters (substrings ‘$0’, ‘$1’ ... ‘$9’) or definitions (substrings ‘$a’, ‘$b’ ... ‘$z’) then before execution the values of parameter/definition will be substituted instead of reference. It allows to use the same MGL script for different parameters (filenames, paths, condition and so on).
-
-
Argument can be a string, a variable (data arrays) or a number (scalars).
-
-
The string is any symbols between ordinary marks ‘'’. Long strings can be concatenated from several lines by ‘\’ symbol. I.e. the string ‘'a +\<br> b'’ will give string ‘'a + b'’ (here ‘<br>’ is newline). There are several operations which can be performed with string:
-
-
Concatenation of strings and numbers using ‘,’ with out spaces (for example, ‘'max(u)=',u.max,' a.u.'’ or ‘'u=',!(1+i2)’ for complex numbers);
-
Getting n-th symbol of the string using ‘[]’ (for example, ‘'abc'[1]’ will give 'b');
-
Adding value to the last character of the string using ‘+’ (for example, ‘'abc'+3’ will give 'abf').
-
-
-
Usually variable have a name which is arbitrary combination of symbols (except spaces and ‘'’) started from a letter. Note, you can start an expression with ‘!’ symbol if you want to use complex values. For example, the code new x 100 'x':copy !b !exp(1i*x) will create real valued data x and complex data b, which is equal to exp(I*x), where I^2=-1. A temporary array can be used as variable too:
-
-
sub-arrays (like in subdata command) as command argument. For example, a(1) or a(1,:) or a(1,:,:) is second row, a(:,2) or a(:,2,:) is third column, a(:,:,0) is first slice and so on. Also you can extract a part of array from m-th to n-th element by code a(m:n,:,:) or just a(m:n).
-
-
any column combinations defined by formulas, like a('n*w^2/exp(t)') if names for data columns was specified (by idset command or in the file at string started with ##).
-
-
any expression (without spaces) of existed variables produce temporary variable. For example, ‘sqrt(dat(:,5)+1)’ will produce temporary variable with data values equal to tmp[i,j] = sqrt(dat[i,5,j]+1). At this symbol ‘`’ will return transposed data array: both ‘`sqrt(dat(:,5)+1)’ and ‘sqrt(`dat(:,5)+1)’ will produce temporary variable with data values equal to tmp[i,j] = sqrt(dat[j,5,i]+1).
-
-
temporary variable of higher dimensions by help of []. For example, ‘[1,2,3]’ will produce a temporary vector of 3 elements {1, 2, 3}; ‘[[11,12],[21,22]]’ will produce matrix 2*2 and so on. Here you can join even an arrays of the same dimensions by construction like ‘[v1,v2,...,vn]’.
-
-
result of code for making new data (see Make another data) inside {}. For example, ‘{sum dat 'x'}’ produce temporary variable which contain result of summation of dat along direction ’x’. This is the same array tmp as produced by command ‘sum tmp dat 'x'’. You can use nested constructions, like ‘{sum {max dat 'z'} 'x'}’.
-
-
Temporary variables can not be used as 1st argument for commands which create (return) the data (like ‘new’, ‘read’, ‘hist’ and so on).
-
-
Special names nan=#QNAN, inf=INFINITY, rnd=random value, pi=3.1415926..., on=1, off=0, all=-1, :=-1, variables with suffixes (see Data information), names defined by define command, time values (in format "hh-mm-ss_DD.MM.YYYY", "hh-mm-ss" or "DD.MM.YYYY") are treated as number. Also results of formulas with sizes 1x1x1 are treated as number (for example, ‘pi/dat.nx’).
-
Command may have several set of possible arguments (for example, plot ydat and plot xdat ydat). All command arguments for a selected set must be specified. However, some arguments can have default values. These argument are printed in [], like text ydat ['stl'=''] or text x y 'txt' ['fnt'='' size=-1]. At this, the record [arg1 arg2 arg3 ...] means [arg1 [arg2 [arg3 ...]]], i.e. you can omit only tailing arguments if you agree with its default values. For example, text x y 'txt' '' 1 or text x y 'txt' '' is correct, but text x y 'txt' 1 is incorrect (argument 'fnt' is missed).
-
-
You can provide several variants of arguments for a command by using ‘?’ symbol for separating them. The actual argument being used is set by variant. At this, the last argument is used if the value of variant is large than the number of provided variants. By default the first argument is used (i.e. as for variant 0). For example, the first plot will be drawn by blue (default is the first argument ‘b’), but the plot after variant 1 will be drawn by red dash (the second is ‘r|’):
-
Below I show commands to control program flow, like, conditions, loops, define script arguments and so on. Other commands can be found in chapters MathGL core and Data processing. Note, that some of program flow commands (like define, ask, call, for, func) should be placed alone in the string.
-
-
-
-
MGL command: chdir'path'
-
Changes the current directory to path.
-
-
-
-
-
MGL command: ask$N 'question'
-
Sets N-th script argument to answer which give the user on the question. Usually this show dialog with question where user can enter some text as answer. Here N is digit (0...9) or alpha (a...z).
-
-
-
-
-
MGL command: define$N smth
-
Sets N-th script argument to smth. Note, that smth is used as is (with ‘'’ symbols if present). Here N is digit (0...9) or alpha (a...z).
-
-
-
MGL command: definename smth
-
Create scalar variable name which have the numeric value of smth. Later you can use this variable as usual number.
-
-
-
-
MGL command: defchr$N smth
-
Sets N-th script argument to character with value evaluated from smth. Here N is digit (0...9) or alpha (a...z).
-
-
-
-
MGL command: defnum$N smth
-
Sets N-th script argument to number with value evaluated from smth. Here N is digit (0...9) or alpha (a...z).
-
-
-
-
-
-
MGL command: call'funcname' [ARG1 ARG2 ... ARG9]
-
Executes function fname (or script if function is not found). Optional arguments will be passed to functions. See also func.
-
-
-
-
MGL command: func'funcname' [narg=0]
-
Define the function fname and number of required arguments. The arguments will be placed in script parameters $1, $2, ... $9. Note, script execution is stopped at func keyword, similarly to stop command. See also return.
-
Load additional MGL command from external module (DLL or .so), located in file filename. This module have to contain array with name mgl_cmd_extra of type mglCommand, which describe provided commands.
-
-
-
-
-
-
MGL command: ifvalthenCMD
-
Executes command CMD only if val is nonzero.
-
-
-
MGL command: ifval
-
Starts block which will be executed if val is nonzero.
-
-
-
MGL command: ifdat 'cond'
-
Starts block which will be executed if dat satisfy to cond.
-
-
-
-
MGL command: elseifval
-
Starts block which will be executed if previous if or elseif is false and val is nonzero.
-
-
-
MGL command: elseifdat 'cond'
-
Starts block which will be executed if previous if or elseif is false and dat satisfy to cond.
-
-
-
-
MGL command: else
-
Starts block which will be executed if previous if or elseif is false.
-
-
-
-
MGL command: endif
-
Finishes if/elseif/else block.
-
-
-
-
-
MGL command: for$N v1 v2 [dv=1]
-
Starts loop with $N-th argument changing from v1 to v2 with the step dv. Here N is digit (0...9) or alpha (a...z).
-
-
-
MGL command: for$N dat
-
Starts loop with $N-th argument changing for dat values. Here N is digit (0...9) or alpha (a...z).
-
-
-
-
MGL command: next
-
Finishes for loop.
-
-
-
-
-
MGL command: do
-
Starts infinite loop.
-
-
-
-
MGL command: whileval
-
Continue loop iterations if val is nonzero, or finishes loop otherwise.
-
-
-
MGL command: whiledat 'cond'
-
Continue loop iterations if dat satisfy to cond, or finishes loop otherwise.
-
-
-
-
-
MGL command: onceval
-
The code between once on and once off will be executed only once. Useful for large data manipulation in programs like UDAV.
-
-
-
-
MGL command: stop
-
Terminate execution.
-
-
-
-
-
MGL command: variantval
-
Set variant of argument(s) separated by ‘?’ symbol to be used in further commands.
-
-
-
-
-
-
MGL command: rkstepeq1;... var1;... [dt=1]
-
Make one step for ordinary differential equation(s) {var1’ = eq1, ... } with time-step dt. Here variable(s) ‘var1’, ... are the ones, defined in MGL script previously. The Runge-Kutta 4-th order method is used for solution.
-
There are number of special comments for MGL script, which set some global behavior (like, animation, dialog for parameters and so on). All these special comments starts with double sign ##. Let consider them.
-
-
-
‘##cv1 v2 [dv=1]’
-
Sets the parameter for animation loop relative to variable $0. Here v1 and v2 are initial and final values, dv is the increment.
-
-
-
‘##a val’
-
Adds the parameter val to the list of animation relative to variable $0. You can use it several times (one parameter per line) or combine it with animation loop ##c.
-
-
-
‘##d $I kind|label|par1|par2|...’
-
Creates custom dialog for changing plot properties. Each line adds one widget to the dialog. Here $I is id ($0,$1...$9,$a,$b...$z), label is the label of widget, kind is the kind of the widget:
-
-
’e’ for editor or input line (parameter is initial value) ,
-
’v’ for spinner or counter (parameters are "ini|min|max|step|big_step"),
-
’s’ for slider (parameters are "ini|min|max|step"),
-
’b’ for check box (parameter is "ini"; also understand "on"=1),
-
’c’ for choice (parameters are possible choices).
-
-
Now, it work in FLTK-based mgllab and mglview only.
-
-
You can make custom dialog in C/C++ code too by using one of following functions.
-
Makes custom dialog for parameters ids of element properties defined by args.
-
-
-
At this you need to provide callback function for setting up properties. You can do it by overloading Param() function of mglDraw class or set it manually.
-
-
-
Method on mglDraw: voidParam(char id, const char * val)
There is LaTeX package mgltex (was made by Diego Sejas Viscarra) which allow one to make figures directly from MGL script located in LaTeX file.
-
-
For using this package you need to specify --shell-escape option for latex/pdflatex or manually run mglconv tool with produced MGL scripts for generation of images. Don’t forgot to run latex/pdflatex second time to insert generated images into the output document. Also you need to run pdflatex third time to update converted from EPS images if you are using vector EPS output (default).
-
-
The package may have following options: draft, final — the same as in the graphicx package; on, off — to activate/deactivate the creation of scripts and graphics; comments, nocomments — to make visible/invisible comments contained inside mglcomment environments; jpg, jpeg, png — to export graphics as JPEG/PNG images; eps, epsz — to export to uncompressed/compressed EPS format as primitives; bps, bpsz — to export to uncompressed/compressed EPS format as bitmap (doesn’t work with pdflatex); pdf — to export to 3D PDF; tex — to export to LaTeX/tikz document.
-
-
The package defines the following environments:
-
-
‘mgl’
-
It writes its contents to a general script which has the same name as the LaTeX document, but its extension is .mgl. The code in this environment is compiled and the image produced is included. It takes exactly the same optional arguments as the \includegraphics command, plus an additional argument imgext, which specifies the extension to save the image.
-
-
An example of usage of ‘mgl’ environment would be:
-
\begin{mglfunc}{prepare2d}
- new a 50 40 '0.6*sin(pi*(x+1))*sin(1.5*pi*(y+1))+0.4*cos(0.75*pi*(x+1)*(y+1))'
- new b 50 40 '0.6*cos(pi*(x+1))*cos(1.5*pi*(y+1))+0.4*cos(0.75*pi*(x+1)*(y+1))'
-\end{mglfunc}
-
-\begin{figure}[!ht]
- \centering
- \begin{mgl}[width=0.85\textwidth,height=7.5cm]
- fog 0.5
- call 'prepare2d'
- subplot 2 2 0 : title 'Surf plot (default)' : rotate 50 60 : light on : box : surf a
-
- subplot 2 2 1 : title '"\#" style; meshnum 10' : rotate 50 60 : box
- surf a '#'; meshnum 10
-
- subplot 2 2 2 : title 'Mesh plot' : rotate 50 60 : box
- mesh a
-
- new x 50 40 '0.8*sin(pi*x)*sin(pi*(y+1)/2)'
- new y 50 40 '0.8*cos(pi*x)*sin(pi*(y+1)/2)'
- new z 50 40 '0.8*cos(pi*(y+1)/2)'
- subplot 2 2 3 : title 'parametric form' : rotate 50 60 : box
- surf x y z 'BbwrR'
- \end{mgl}
-\end{figure}
-
-
-
‘mgladdon’
-
It adds its contents to the general script, without producing any image.
-
-
‘mglcode’
-
Is exactly the same as ‘mgl’, but it writes its contents verbatim to its own file, whose name is specified as a mandatory argument.
-
-
‘mglscript’
-
Is exactly the same as ‘mglcode’, but it doesn’t produce any image, nor accepts optional arguments. It is useful, for example, to create a MGL script, which can later be post processed by another package like "listings".
-
-
‘mglblock’
-
It writes its contents verbatim to a file, specified as a mandatory argument, and to the LaTeX document, and numerates each line of code.
-
-
-
‘mglverbatim’
-
Exactly the same as ‘mglblock’, but it doesn’t write to a file. This environment doesn’t have arguments.
-
-
‘mglfunc’
-
Is used to define MGL functions. It takes one mandatory argument, which is the name of the function, plus one additional argument, which specifies the number of arguments of the function. The environment needs to contain only the body of the function, since the first and last lines are appended automatically, and the resulting code is written at the end of the general script, after the stop command, which is also written automatically. The warning is produced if 2 or more function with the same name is defined.
-
-
‘mglcomment’
-
Is used to contain multiline comments. This comments will be visible/invisible in the output document, depending on the use of the package options comments and nocomments (see above), or the \mglcomments and \mglnocomments commands (see bellow).
-
-
‘mglsetup’
-
If many scripts with the same code are to be written, the repetitive code can be written inside this environment only once, then this code will be used automatically every time the ‘\mglplot’ command is used (see below). It takes one optional argument, which is a name to be associated to the corresponding contents of the environment; this name can be passed to the ‘\mglplot’ command to use the corresponding block of code automatically (see below).
-
-
-
-
The package also defines the following commands:
-
-
‘\mglplot’
-
It takes one mandatory argument, which is MGL instructions separated by the symbol ‘:’ this argument can be more than one line long. It takes the same optional arguments as the ‘mgl’ environment, plus an additional argument setup, which indicates the name associated to a block of code inside a ‘mglsetup’ environment. The code inside the mandatory argument will be appended to the block of code specified, and the resulting code will be written to the general script.
-
-
An example of usage of ‘\mglplot’ command would be:
-
This command takes the same optional arguments as the ‘mgl’ environment, and one mandatory argument, which is the name of a MGL script. This command will compile the corresponding script and include the resulting image. It is useful when you have a script outside the LaTeX document, and you want to include the image, but you don’t want to type the script again.
-
-
‘\mglinclude’
-
This is like ‘\mglgraphics’ but, instead of creating/including the corresponding image, it writes the contents of the MGL script to the LaTeX document, and numerates the lines.
-
-
‘\mgldir’
-
This command can be used in the preamble of the document to specify a directory where LaTeX will save the MGL scripts and generate the corresponding images. This directory is also where ‘\mglgraphics’ and ‘\mglinclude’ will look for scripts.
-
-
‘\mglquality’
-
Adjust the quality of the MGL graphics produced similarly to quality.
-
-
‘\mgltexon, \mgltexoff’
-
Activate/deactivate the creation of MGL scripts and images. Notice these commands have local behavior in the sense that their effect is from the point they are called on.
-
-
‘\mglcomment, \mglnocomment’
-
Make visible/invisible the contents of the mglcomment environments. These commands have local effect too.
-
-
‘\mglTeX’
-
It just pretty prints the name of the package.
-
-
-
-
As an additional feature, when an image is not found or cannot be included, instead of issuing an error, mgltex prints a box with the word ‘MGL image not found’ in the LaTeX document.
-
Class for parsing and executing MGL script. This class is defined in #include <mgl2/mgl.h>.
-
-
The main function of mglParse class is Execute(). Exactly this function parses and executes the script string-by-string. Also there are subservient functions for the finding and creation of a variable (object derived from mglDataA). These functions can be useful for displaying values of variables (arrays) in some external object (like, window) or for providing access to internal data. Function AllowSetSize() allows one to prevent changing the size of the picture inside the script (forbids the MGL command setsize).
-
-
-
-
Constructor on mglParse: mglParse(bool setsize=false)
-
Constructor on mglParse: mglParse(HMPR pr)
-
Constructor on mglParse: mglParse(mglParse &pr)
-
C function: HMPRmgl_create_parser()
-
Constructor initializes all values with zero and set AllowSetSize value.
-
-
-
-
Destructor on mglParse: ~mglParse()
-
C function: voidmgl_delete_parser(HMPR p)
-
Destructor delete parser
-
-
-
-
Method on mglParse: HMPRSelf()
-
Returns the pointer to internal object of type HMPR.
-
-
-
-
Method on mglParse: voidExecute(mglGraph *gr, const char *text)
-
Method on mglParse: voidExecute(mglGraph *gr, const wchar_t *text)
-
C function: voidmgl_parse_text(HMGL gr, HMPR p, const char *text)
-
C function: voidmgl_parse_textw(HMGL gr, HMPR p, const wchar_t *text)
-
Main function in the class. Function parse and execute line-by-line MGL script in array text. Lines are separated by newline symbol ‘\n’ as usual.
-
-
-
-
Method on mglParse: voidExecute(mglGraph *gr, FILE *fp, bool print=false)
-
C function: voidmgl_parse_file(HMGL gr, HMPR p, FILE *fp, int print)
-
The same as previous but read script from the file fp. If print=true then all warnings and information will be printed in stdout.
-
-
-
-
Method on mglParse: intParse(mglGraph *gr, const char *str, long pos=0)
-
Method on mglParse: intParse(mglGraph *gr, const wchar_t *str, long pos=0)
-
C function: intmgl_parse_line(HMGL gr, HMPR p, const char *str, int pos)
-
C function: intmgl_parse_linew(HMGL gr, HMPR p, const wchar_t *str, int pos)
-
Function parses the string str and executes it by using gr as a graphics plotter. Returns the value depending on an error presence in the string str: 0 – no error, 1 – wrong command argument(s), 2 – unknown command, 3 – string is too long, 4 – strings is not closed. Optional argument pos allows to save the string position in the document (or file) for using for|next command.
-
-
-
-
Method on mglParse: mglDataCalc(const char *formula)
-
Method on mglParse: mglDataCalc(const wchar_t *formula)
-
C function: HMDTmgl_parser_calc(HMPR p, const char *formula)
-
C function: HMDTmgl_parser_calcw(HMPR p, const wchar_t *formula)
-
Function parses the string formula and return resulting data array. In difference to AddVar() or FindVar(), it is usual data array which should be deleted after usage.
-
-
-
-
Method on mglParse: mglDataCCalcComplex(const char *formula)
-
Method on mglParse: mglDataCCalcComplex(const wchar_t *formula)
-
C function: HADTmgl_parser_calc_complex(HMPR p, const char *formula)
-
C function: HADTmgl_parser_calc_complexw(HMPR p, const wchar_t *formula)
-
Function parses the string formula and return resulting data array with complex values. In difference to AddVar() or FindVar(), it is usual data array which should be deleted after usage.
-
-
-
-
Method on mglParse: voidAddParam(int n, const char *str)
-
Method on mglParse: voidAddParam(int n, const wchar_t *str)
-
C function: voidmgl_parser_add_param(HMPR p, int id, const char *val)
-
C function: voidmgl_parser_add_paramw(HMPR p, int id, const wchar_t *val)
-
Function set the value of n-th parameter as string str (n=0, 1 ... ’z’-’a’+10). String str shouldn’t contain ‘$’ symbol.
-
-
-
-
Method on mglParse: mglVar *FindVar(const char *name)
-
Method on mglParse: mglVar *FindVar(const wchar_t *name)
-
C function: HMDTmgl_parser_find_var(HMPR p, const char *name)
-
C function: HMDTmgl_parser_find_varw(HMPR p, const wchar_t *name)
-
Function returns the pointer to variable with name name or zero if variable is absent. Use this function to put external data array to the script or get the data from the script. You must not delete obtained data arrays!
-
-
-
Method on mglParse: mglVar *AddVar(const char *name)
-
Method on mglParse: mglVar *AddVar(const wchar_t *name)
-
C function: HMDTmgl_parser_add_var(HMPR p, const char *name)
-
C function: HMDTmgl_parser_add_varw(HMPR p, const wchar_t *name)
-
Function returns the pointer to variable with name name. If variable is absent then new variable is created with name name. Use this function to put external data array to the script or get the data from the script. You must not delete obtained data arrays!
-
-
-
-
Method on mglParse: voidOpenHDF(const char *fname)
-
C function: voidmgl_parser_openhdf(HMPR pr, const char *fname)
-
Reads all data array from HDF5 file fname and create MGL variables with names of data names in HDF file. Complex variables will be created if data name starts with ‘!’.
-
-
-
-
Method on mglParse (C++): voidDeleteVar(const char *name)
-
Method on mglParse (C++): voidDeleteVar(const wchar_t *name)
-
C function: voidmgl_parser_del_var(HMPR p, const char *name)
-
C function: voidmgl_parser_del_varw(HMPR p, const wchar_t *name)
-
Function delete the variable with given name.
-
-
-
-
Method on mglParse (C++): voidDeleteAll()
-
C function: voidmgl_parser_del_all(HMPR p)
-
Function delete all variables and reset list of commands to default one in this parser.
-
-
-
-
Method on mglParse: voidRestoreOnce()
-
C function: voidmgl_parser_restore_once(HMPR p)
-
Restore Once flag.
-
-
-
-
Method on mglParse: voidAllowSetSize(bool a)
-
C function: voidmgl_parser_allow_setsize(HMPR p, int a)
Make one step for ordinary differential equation(s) {var1’ = eq1, ... } with time-step dt. Here strings eqs and vars contain the equations and variable names separated by symbol ‘;’. The variable(s) ‘var1’, ... are the ones, defined in MGL script previously. The Runge-Kutta 4-th order method is used.
-
UDAV (Universal Data Array Visualizator) is cross-platform program for data arrays visualization based on MathGL library. It support wide spectrum of graphics, simple script language and visual data handling and editing. It has window interface for data viewing, changing and plotting. Also it can execute MGL scripts, setup and rotate graphics and so on. UDAV hot-keys can be found in the appendix Hot-keys for UDAV.
-
UDAV have main window divided by 2 parts in general case and optional bottom panel(s). Left side contain tabs for MGL script and data arrays. Right side contain tabs with graphics itself, with list of variables and with help on MGL. Bottom side may contain the panel with MGL messages and warnings, and the panel with calculator.
-
-
-
-
Main window is shown on the figure above. You can see the script (at left) with current line highlighted by light-yellow, and result of its execution at right. Each panel have its own set of toolbuttons.
-
-
Editor toolbuttons allow: open and save script from/to file; undo and redo changes; cut, copy and paste selection; find/replace text; show dialogs for command arguments and for plot setup; show calculator at bottom.
-
-
Graphics toolbuttons allow: enable/disable additional transparency and lighting; show grid of absolute coordinates; enable mouse rotation; restore image view; refresh graphics (execute the script); stop calculation; copy graphics into clipboard; add primitives (line, curve, box, rhombus, ellipse, mark, text) to the image; change view angles manually. Vertical toolbuttons allow: shift and zoom in/out of image as whole; show next and previous frame of animation, or start animation (if one present).
-
-
Graphics panel support plot editing by mouse.
-
-
Axis range can be changed by mouse wheel or by dragging image by middle mouse button. Right button show popup menu. Left button show the coordinates of mouse click. At this double click will highlight plot under mouse and jump to the corresponded string of the MGL script.
-
Pressing "mouse rotation" toolbutton will change mouse actions: dragging by left button will rotate plot, middle button will shift the plot as whole, right button will zoom in/out plot as whole and add perspective, mouse wheel will zoom in/out plot as whole.
-
Manual primitives can be added by pressing corresponding toolbutton. They can be shifted as whole at any time by mouse dragging. At this double click open dialog with its properties. If toolbutton "grid of absolute coordinates" is pressed then editing of active points for primitives is enabled.
-
-
-
-
-
Short command description and list of its arguments are shown at the status-bar, when you move cursor to the new line of code. You can press F1 to see more detailed help on special panel.
-
-
-
-
Also you can look the current list of variables, its dimensions and its size in the memory (right side of above figure). Toolbuttons allow: create new variable, edit variable, delete variable, preview variable plot and its properties, refresh list of variables. Pressing on any column will sort table according its contents. Double click on a variable will open panel with data cells of the variable, where you can view/edit each cell independently or apply a set of transformations.
-
-
-
-
Finally, pressing F2 or F4 you can show/hide windows with messages/warnings and with calculator. Double click on a warning in message window will jump to corresponding line in editor. Calculator allow you type expression by keyboard as well as by toolbuttons. It know about all current variables, so you can use them in formulas.
-
There are a set of dialogs, which allow change/add a command, setup global plot properties, or setup UDAV itself.
-
-
-
-
One of most interesting dialog (hotkey Meta-C or Win-C) is dialog which help to enter new command or change arguments of existed one. It allows consequently select the category of command, command name in category and appropriate set of command arguments. At this right side show detailed command description. Required argument(s) are denoted by bold text. Strings are placed in apostrophes, like 'txt'. Buttons below table allow to call dialogs for changing style of command (if argument 'fmt' is present in the list of command arguments); to set variable or expression for argument(s); to add options for command. Note, you can click on a cell to enter value, or double-click to call corresponding dialog.
-
-
-
-
-
-
-
Dialog for changing style can be called independently, but usually is called from New command dialog or by double click on primitive. It contain 3 tabs: one for pen style, one for color scheme, one for text style. You should select appropriate one. Resulting string of style and sample picture are shown at bottom of dialog. Usually it can be called from New command dialog.
-
-
-
-
Dialog for entering variable allow to select variable or expression which can be used as argument of a command. Here you can select the variable name; range of indexes in each directions; operation which will be applied (like, summation, finding minimal/maximal values and so on). Usually it can be called from New command dialog.
-
-
-
-
Dialog for command options allow to change Command options. Usually it can be called from New command dialog.
-
-
-
-
-
-
Another interesting dialog, which help to select and properly setup a subplot, inplot, columnplot, stickplot and similar commands.
-
-
-
-
-
-
There is dialog for setting general plot properties, including tab for setting lighting properties. It can be called by called by hotkey ??? and put setup commands at the beginning of MGL script.
-
-
-
-
Also you can set or change script parameters (‘$0’ ... ‘$9’, see MGL definition).
-
-
-
-
Finally, there is dialog for UDAV settings. It allow to change most of things in UDAV appearance and working, including colors of keywords and numbers, default font and image size, and so on (see figure above).
-
-
There are also a set of dialogs for data handling, but they are too simple and clear. So, I will not put them here.
-
You can shift axis range by pressing middle button and moving mouse. Also, you can zoom in/out axis range by using mouse wheel.
-
You can rotate/shift/zoom whole plot by mouse. Just press ’Rotate’ toolbutton, click image and hold a mouse button: left button for rotation, right button for zoom/perspective, middle button for shift.
-
You may quickly draw the data from file. Just use: udav ’filename.dat’ in command line.
-
You can copy the current image to clipboard by pressing Ctrl-Shift-C. Later you can paste it directly into yours document or presentation.
-
You can export image into a set of format (EPS, SVG, PNG, JPEG) by pressing right mouse button inside image and selecting ’Export as ...’.
-
You can setup colors for script highlighting in Property dialog. Just select menu item ’Settings/Properties’.
-
You can save the parameter of animation inside MGL script by using comment started from ’##a ’ or ’##c ’ for loops.
-
New drawing never clears things drawn already. For example, you can make a surface with contour lines by calling commands ’surf’ and ’cont’ one after another (in any order).
-
You can put several plots in the same image by help of commands ’subplot’ or ’inplot’.
-
All indexes (of data arrays, subplots and so on) are always start from 0.
-
You can edit MGL file in any text editor. Also you can run it in console by help of commands: mglconv, mglview.
-
You can use command ’once on|off’ for marking the block which should be executed only once. For example, this can be the block of large data reading/creating/handling. Press F9 (or menu item ’Graphics/Reload’) to re-execute this block.
-
You can use command ’stop’ for terminating script parsing. It is useful if you don’t want to execute a part of script.
-
You can type arbitrary expression as input argument for data or number. In last case (for numbers), the first value of data array is used.
-
There is powerful calculator with a lot of special functions. You can use buttons or keyboard to type the expression. Also you can use existed variables in the expression.
-
The calculator can help you to put complex expression in the script. Just type the expression (which may depend on coordinates x,y,z and so on) and put it into the script.
-
You can easily insert file or folder names, last fitted formula or numerical value of selection by using menu Edit|Insert.
-
The special dialog (Edit|Insert|New Command) help you select the command, fill its arguments and put it into the script.
-
You can put several plotting commands in the same line or in separate function, for highlighting all of them simultaneously.
-
There are few end-user classes: mglGraph (see MathGL core), mglWindow and mglGLUT (see Widget classes), mglData (see Data processing), mglParse (see MGL scripts). Exactly these classes I recommend to use in most of user programs. All methods in all of these classes are inline and have exact C/Fortran analogue functions. This give compiler independent binary libraries for MathGL.
-
-
However, sometimes you may need to extend MathGL by writing yours own plotting functions or handling yours own data structures. In these cases you may need to use low-level API. This chapter describes it.
-
-
-
-
The internal structure of MathGL is rather complicated. There are C++ classes mglBase, mglCanvas, ... for drawing primitives and positioning the plot (blue ones in the figure). There is a layer of C functions, which include interface for most important methods of these classes. Also most of plotting functions are implemented as C functions. After it, there are “inline” front-end classes which are created for user convenience (yellow ones in the figure). Also there are widgets for FLTK and Qt libraries (green ones in the figure).
-
-
Below I show how this internal classes can be used.
-
Basically most of new kinds of plot can be created using just MathGL primitives (see Primitives). However the usage of mglBase methods can give you higher speed of drawing and better control of plot settings.
-
-
All plotting functions should use a pointer to mglBase class (or HMGL type in C functions) due to compatibility issues. Exactly such type of pointers are used in front-end classes (mglGraph, mglWindow) and in widgets (QMathGL, Fl_MathGL).
-
-
MathGL tries to remember all vertexes and all primitives and plot creation stage, and to use them for making final picture by demand. Basically for making plot, you need to add vertexes by AddPnt() function, which return index for new vertex, and call one of primitive drawing function (like mark_plot(), arrow_plot(), line_plot(), trig_plot(), quad_plot(), text_plot()), using vertex indexes as argument(s). AddPnt() function use 2 mreal numbers for color specification. First one is positioning in textures – integer part is texture index, fractional part is relative coordinate in the texture. Second number is like a transparency of plot (or second coordinate in the 2D texture).
-
-
I don’t want to put here detailed description of mglBase class. It was rather well documented in mgl2/base.h file. I just show and example of its usage on the base of circle drawing.
-
-
First, we should prototype new function circle() as C function.
-
First, we need to check all input arguments and send warnings if something is wrong. In our case it is negative value of r argument. We just send warning, since it is not critical situation – other plot still can be drawn.
-
Next step is creating a group. Group keep some general setting for plot (like options) and useful for export in 3d files.
-
static int cgid=1; gr->StartGroup("Circle",cgid++);
-
Now let apply options. Options are rather useful things, generally, which allow one easily redefine axis range(s), transparency and other settings (see Command options).
-
gr->SaveState(opt);
-
I use global setting for determining the number of points in circle approximation. Note, that user can change MeshNum by options easily.
-
const int n = gr->MeshNum>1?gr->MeshNum : 41;
-
Let try to determine plot specific flags. MathGL functions expect that most of flags will be sent in string. In our case it is symbol ‘@’ which set to draw filled circle instead of border only (last will be default). Note, you have to handle NULL as string pointer.
-
bool fill = mglchr(stl,'@');
-
Now, time for coloring. I use palette mechanism because circle have few colors: one for filling and another for border. SetPenPal() function parse input string and write resulting texture index in pal. Function return the character for marker, which can be specified in string str. Marker will be plotted at the center of circle. I’ll show on next sample how you can use color schemes (smooth colors) too.
-
long pal=0;
- char mk=gr->SetPenPal(stl,&pal);
-
Next step, is determining colors for filling and for border. First one for filling.
-
mreal c=gr->NextColor(pal), d;
-
Second one for border. I use black color (call gr->AddTexture('k')) if second color is not specified.
-
If user want draw only border (fill=false) then I use first color for border.
-
if(!fill) k=c;
-
Now we should reserve space for vertexes. This functions need n for border, n+1 for filling and 1 for marker. So, maximal number of vertexes is 2*n+2. Note, that such reservation is not required for normal work but can sufficiently speed up the plotting.
-
gr->Reserve(2*n+2);
-
We’ve done with setup and ready to start drawing. First, we need to add vertex(es). Let define NAN as normals, since I don’t want handle lighting for this plot,
-
mglPoint q(NAN,NAN);
-
and start adding vertexes. First one for central point of filling. I use -1 if I don’t need this point. The arguments of AddPnt() function is: mglPoint(x,y,z) – coordinate of vertex, c – vertex color, q – normal at vertex, -1 – vertex transparency (-1 for default), 3 bitwise flag which show that coordinates will be scaled (0x1) and will not be cutted (0x2).
-
long n0,n1,n2,m1,m2,i;
- n0 = fill ? gr->AddPnt(mglPoint(x,y,z),c,q,-1,3):-1;
-
Similar for marker, but we use different color k.
-
Time for drawing circle itself. I use -1 for m1, n1 as sign that primitives shouldn’t be drawn for first point i=0.
-
for(i=0,m1=n1=-1;i<n;i++)
- {
-
Each function should check Stop variable and return if it is non-zero. It is done for interrupting drawing for system which don’t support multi-threading.
-
if(gr->Stop) return;
-
Let find coordinates of vertex.
-
mreal t = i*2*M_PI/(n-1.);
- mglPoint p(x+r*cos(t), y+r*sin(t), z);
-
Save previous vertex and add next one
-
n2 = n1; n1 = gr->AddPnt(p,c,q,-1,3);
-
and copy it for border but with different color. Such copying is much faster than adding new vertex using AddPnt().
-
m2 = m1; m1 = gr->CopyNtoC(n1,k);
-
Now draw triangle for filling internal part
-
if(fill) gr->trig_plot(n0,n1,n2);
-
and draw line for border.
-
gr->line_plot(m1,m2);
- }
-
Drawing is done. Let close group and return.
-
gr->EndGroup();
-}
-
-
Another sample I want to show is exactly the same function but with smooth coloring using color scheme. So, I’ll add comments only in the place of difference.
-
In this case let allow negative radius too. Formally it is not the problem for plotting (formulas the same) and this allow us to handle all color range.
-
//if(r<=0) { gr->SetWarn(mglWarnNeg,"Circle"); return; }
-
- static int cgid=1; gr->StartGroup("CircleCS",cgid++);
- gr->SaveState(opt);
- const int n = gr->MeshNum>1?gr->MeshNum : 41;
- bool fill = mglchr(stl,'@');
-
Here is main difference. We need to create texture for color scheme specified by user
-
long ss = gr->AddTexture(stl);
-
But we need also get marker and color for it (if filling is enabled). Let suppose that marker and color is specified after ‘:’. This is standard delimiter which stop color scheme entering. So, just lets find it and use for setting pen.
-
The last thing which we can do is derive our own class with new plotting functions. Good idea is to derive it from mglGraph (if you don’t need extended window), or from mglWindow (if you need to extend window). So, in our case it will be
-
mglData class have abstract predecessor class mglDataA. Exactly the pointers to mglDataA instances are used in all plotting functions and some of data processing functions. This was done for taking possibility to define yours own class, which will handle yours own data (for example, complex numbers, or differently organized data). And this new class will be almost the same as mglData for plotting purposes.
-
-
However, the most of data processing functions will be slower as if you used mglData instance. This is more or less understandable – I don’t know how data in yours particular class will be organized, and couldn’t optimize the these functions generally.
-
-
There are few virtual functions which must be provided in derived classes. This functions give:
-
-
the sizes of the data (GetNx, GetNy, GetNz),
-
give data value and numerical derivatives for selected cell (v, dvx, dvy, dvz),
-
give maximal and minimal values (Maximal, Minimal) – you can use provided functions (like mgl_data_max and mgl_data_min), but yours own realization can be more efficient,
-
give access to all element as in single array (vthr) – you need this only if you want using MathGL’s data processing functions.
-
-
-
Let me, for example define class mglComplex which will handle complex number and draw its amplitude or phase, depending on flag use_abs:
-
#include <complex>
-#include <mgl2/mgl.h>
-#define dual std::complex<double>
-class mglComplex : public mglDataA
-{
-public:
- long nx; ///< number of points in 1st dimensions ('x' dimension)
- long ny; ///< number of points in 2nd dimensions ('y' dimension)
- long nz; ///< number of points in 3d dimensions ('z' dimension)
- dual *a; ///< data array
- bool use_abs; ///< flag to use abs() or arg()
-
- inline mglComplex(long xx=1,long yy=1,long zz=1)
- { a=0; use_abs=true; Create(xx,yy,zz); }
- virtual ~mglComplex() { if(a) delete []a; }
-
- /// Get sizes
- inline long GetNx() const { return nx; }
- inline long GetNy() const { return ny; }
- inline long GetNz() const { return nz; }
- /// Create or recreate the array with specified size and fill it by zero
- inline void Create(long mx,long my=1,long mz=1)
- { nx=mx; ny=my; nz=mz; if(a) delete []a;
- a = new dual[nx*ny*nz]; }
- /// Get maximal value of the data
- inline mreal Maximal() const { return mgl_data_max(this); }
- /// Get minimal value of the data
- inline mreal Minimal() const { return mgl_data_min(this); }
-
-protected:
- inline mreal v(long i,long j=0,long k=0) const
- { return use_abs ? abs(a[i+nx*(j+ny*k)]) : arg(a[i+nx*(j+ny*k)]); }
- inline mreal vthr(long i) const
- { return use_abs ? abs(a[i]) : arg(a[i]); }
- inline mreal dvx(long i,long j=0,long k=0) const
- { long i0=i+nx*(j+ny*k);
- std::complex<double> res=i>0? (i<nx-1? (a[i0+1]-a[i0-1])/2.:a[i0]-a[i0-1]) : a[i0+1]-a[i0];
- return use_abs? abs(res) : arg(res); }
- inline mreal dvy(long i,long j=0,long k=0) const
- { long i0=i+nx*(j+ny*k);
- std::complex<double> res=j>0? (j<ny-1? (a[i0+nx]-a[i0-nx])/2.:a[i0]-a[i0-nx]) : a[i0+nx]-a[i0];
- return use_abs? abs(res) : arg(res); }
- inline mreal dvz(long i,long j=0,long k=0) const
- { long i0=i+nx*(j+ny*k), n=nx*ny;
- std::complex<double> res=k>0? (k<nz-1? (a[i0+n]-a[i0-n])/2.:a[i0]-a[i0-n]) : a[i0+n]-a[i0];
- return use_abs? abs(res) : arg(res); }
-};
-int main()
-{
- mglComplex dat(20);
- for(long i=0;i<20;i++)
- dat.a[i] = 3*exp(-0.05*(i-10)*(i-10))*dual(cos(M_PI*i*0.3), sin(M_PI*i*0.3));
- mglGraph gr;
- gr.SetRange('y', -M_PI, M_PI); gr.Box();
-
- gr.Plot(dat,"r","legend 'abs'");
- dat.use_abs=false;
- gr.Plot(dat,"b","legend 'arg'");
- gr.Legend();
- gr.WritePNG("complex.png");
- return 0;
-}
-
Structure for working with colors. This structure is defined in #include <mgl2/type.h>.
-
-
There are two ways to set the color in MathGL. First one is using of mreal values of red, green and blue channels for precise color definition. The second way is the using of character id. There are a set of characters specifying frequently used colors. Normally capital letter gives more dark color than lowercase one. See Line styles.
-
Function axial draw surfaces of rotation for contour lines. You can draw wire surfaces (‘#’ style) or ones rotated in other directions (‘x’, ‘z’ styles).
-
Function bars draw vertical bars. It have a lot of options: bar-above-bar (‘a’ style), fall like (‘f’ style), 2 colors for positive and negative values, wired bars (‘#’ style), 3D variant.
-
Function candle draw candlestick chart. This is a combination of a line-chart and a bar-chart, in that each bar represents the range of price movement over a given time interval.
-
-
MGL code:
-
new y 30 'sin(pi*x/2)^2'
-subplot 1 1 0 '':title 'Candle plot (default)'
-yrange 0 1:box
-candle y y/2 (y+1)/2
-
Function chart draw colored boxes with width proportional to data values. Use ‘’ for empty box. It produce well known pie chart if drawn in polar coordinates.
-
Function cloud draw cloud-like object which is less transparent for higher data values. Similar plot can be created using many (about 10...20 – surf3a a a;value 10) isosurfaces surf3a.
-
call 'prepare2v'
-call 'prepare3d'
-new v 10:fill v -0.5 1:copy d sqrt(a^2+b^2)
-subplot 2 2 0:title 'Surf + Cont':rotate 50 60:light on:box:surf a:cont a 'y'
-subplot 2 2 1 '':title 'Flow + Dens':light off:box:flow a b 'br':dens d
-subplot 2 2 2:title 'Mesh + Cont':rotate 50 60:box:mesh a:cont a '_'
-subplot 2 2 3:title 'Surf3 + ContF3':rotate 50 60:light on
-box:contf3 v c 'z' 0:contf3 v c 'x':contf3 v c
-cut 0 -1 -1 1 0 1.1
-contf3 v c 'z' c.nz-1:surf3 c -0.5
-
Function cont draw contour lines for surface. You can select automatic (default) or manual levels for contours, print contour labels, draw it on the surface (default) or at plane (as Dens).
-
-
MGL code:
-
call 'prepare2d'
-list v -0.5 -0.15 0 0.15 0.5
-subplot 2 2 0:title 'Cont plot (default)':rotate 50 60:box:cont a
-subplot 2 2 1:title 'manual levels':rotate 50 60:box:cont v a
-subplot 2 2 2:title '"\_" and "." styles':rotate 50 60:box:cont a '_':cont a '_.2k'
-subplot 2 2 3 '':title '"t" style':box:cont a 't'
-
Functions contz, conty, contx draw contour lines on plane perpendicular to corresponding axis. One of possible application is drawing projections of 3D field.
-
-
MGL code:
-
call 'prepare3d'
-title 'Cont[XYZ] sample':rotate 50 60:box
-contx {sum c 'x'} '' -1:conty {sum c 'y'} '' 1:contz {sum c 'z'} '' -1
-
Functions contfz, contfy, contfx, draw filled contours on plane perpendicular to corresponding axis. One of possible application is drawing projections of 3D field.
-
-
MGL code:
-
call 'prepare3d'
-title 'ContF[XYZ] sample':rotate 50 60:box
-contfx {sum c 'x'} '' -1:contfy {sum c 'y'} '' 1:contfz {sum c 'z'} '' -1
-
new a 100 'exp(-10*x^2)'
-new b 100 'exp(-10*(x+0.5)^2)'
-yrange 0 1
-subplot 1 2 0 '_':title 'Input fields'
-plot a:plot b:box:axis
-correl r a b 'x'
-norm r 0 1:swap r 'x' # make it human readable
-subplot 1 2 1 '_':title 'Correlation of a and b'
-plot r 'r':axis:box
-line 0.5 0 0.5 1 'B|'
-
-
C++ code:
-
void smgl_correl(mglGraph *gr)
-{
- mglData a(100),b(100);
- gr->Fill(a,"exp(-10*x^2)"); gr->Fill(b,"exp(-10*(x+0.5)^2)");
- gr->SetRange('y',0,1);
- gr->SubPlot(1,2,0,"_"); gr->Title("Input fields");
- gr->Plot(a); gr->Plot(b); gr->Axis(); gr->Box();
- mglData r = a.Correl(b,"x");
- r.Norm(0,1); r.Swap("x"); // make it human readable
- gr->SubPlot(1,2,1,"_"); gr->Title("Correlation of a and b");
- gr->Plot(r,"r"); gr->Axis(); gr->Box();
- gr->Line(mglPoint(0.5,0),mglPoint(0.5,1),"B|");
-}
-
new a 40 50 60 'exp(-x^2-4*y^2-16*z^2)'
-light on:alpha on
-copy b a:diff b 'x':subplot 5 3 0:call 'splot'
-copy b a:diff2 b 'x':subplot 5 3 1:call 'splot'
-copy b a:cumsum b 'x':subplot 5 3 2:call 'splot'
-copy b a:integrate b 'x':subplot 5 3 3:call 'splot'
-mirror b 'x':subplot 5 3 4:call 'splot'
-copy b a:diff b 'y':subplot 5 3 5:call 'splot'
-copy b a:diff2 b 'y':subplot 5 3 6:call 'splot'
-copy b a:cumsum b 'y':subplot 5 3 7:call 'splot'
-copy b a:integrate b 'y':subplot 5 3 8:call 'splot'
-mirror b 'y':subplot 5 3 9:call 'splot'
-copy b a:diff b 'z':subplot 5 3 10:call 'splot'
-copy b a:diff2 b 'z':subplot 5 3 11:call 'splot'
-copy b a:cumsum b 'z':subplot 5 3 12:call 'splot'
-copy b a:integrate b 'z':subplot 5 3 13:call 'splot'
-mirror b 'z':subplot 5 3 14:call 'splot'
-stop
-func splot 0
-title 'max=',b.max:norm b -1 1 on:rotate 70 60:box:surf3 b
-return
-
new a 40 50 60 'exp(-x^2-4*y^2-16*z^2)'
-light on:alpha on
-copy b a:sinfft b 'x':subplot 5 3 0:call 'splot'
-copy b a:cosfft b 'x':subplot 5 3 1:call 'splot'
-copy b a:hankel b 'x':subplot 5 3 2:call 'splot'
-copy b a:swap b 'x':subplot 5 3 3:call 'splot'
-copy b a:smooth b 'x':subplot 5 3 4:call 'splot'
-copy b a:sinfft b 'y':subplot 5 3 5:call 'splot'
-copy b a:cosfft b 'y':subplot 5 3 6:call 'splot'
-copy b a:hankel b 'y':subplot 5 3 7:call 'splot'
-copy b a:swap b 'y':subplot 5 3 8:call 'splot'
-copy b a:smooth b 'y':subplot 5 3 9:call 'splot'
-copy b a:sinfft b 'z':subplot 5 3 10:call 'splot'
-copy b a:cosfft b 'z':subplot 5 3 11:call 'splot'
-copy b a:hankel b 'z':subplot 5 3 12:call 'splot'
-copy b a:swap b 'z':subplot 5 3 13:call 'splot'
-copy b a:smooth b 'z':subplot 5 3 14:call 'splot'
-stop
-func splot 0
-title 'max=',b.max:norm b -1 1 on:rotate 70 60:box
-surf3 b 0.5:surf3 b -0.5
-return
-
Functions densz, densy, densx draw density plot on plane perpendicular to corresponding axis. One of possible application is drawing projections of 3D field.
-
-
MGL code:
-
call 'prepare3d'
-title 'Dens[XYZ] sample':rotate 50 60:box
-densx {sum c 'x'} '' -1:densy {sum c 'y'} '' 1:densz {sum c 'z'} '' -1
-
define n 32 #number of points
-define m 20 # number of iterations
-define dt 0.01 # time step
-new res n m+1
-ranges -1 1 0 m*dt 0 1
-
-#tridmat periodic variant
-new !a n 'i',dt*(n/2)^2/2
-copy !b !(1-2*a)
-
-new !u n 'exp(-6*x^2)'
-put res u all 0
-for $i 0 m
-tridmat u a b a u 'xdc'
-put res u all $i+1
-next
-subplot 2 2 0 '<_':title 'Tridmat, periodic b.c.'
-axis:box:dens res
-
-#fourier variant
-new k n:fillsample k 'xk'
-copy !e !exp(-i1*dt*k^2)
-
-new !u n 'exp(-6*x^2)'
-put res u all 0
-for $i 0 m
-fourier u 'x'
-multo u e
-fourier u 'ix'
-put res u all $i+1
-next
-subplot 2 2 1 '<_':title 'Fourier method'
-axis:box:dens res
-
-#tridmat zero variant
-new !u n 'exp(-6*x^2)'
-put res u all 0
-for $i 0 m
-tridmat u a b a u 'xd'
-put res u all $i+1
-next
-subplot 2 2 2 '<_':title 'Tridmat, zero b.c.'
-axis:box:dens res
-
-#diffract exp variant
-new !u n 'exp(-6*x^2)'
-define q dt*(n/2)^2/8 # need q<0.4 !!!
-put res u all 0
-for $i 0 m
-for $j 1 8 # due to smaller dt
-diffract u 'xe' q
-next
-put res u all $i+1
-next
-subplot 2 2 3 '<_':title 'Diffract, exp b.c.'
-axis:box:dens res
-
Function dots is another way to draw irregular points. Dots use color scheme for coloring (see Color scheme).
-
-
MGL code:
-
new t 2000 'pi*(rnd-0.5)':new f 2000 '2*pi*rnd'
-copy x 0.9*cos(t)*cos(f):copy y 0.9*cos(t)*sin(f):copy z 0.6*sin(t):copy c cos(2*t)
-subplot 2 2 0:title 'Dots sample':rotate 50 60
-box:dots x y z
-alpha on
-subplot 2 2 1:title 'add transparency':rotate 50 60
-box:dots x y z c
-subplot 2 2 2:title 'add colorings':rotate 50 60
-box:dots x y z x c
-subplot 2 2 3:title 'Only coloring':rotate 50 60
-box:tens x y z x ' .'
-
import dat 'Equirectangular-projection.jpg' 'BbGYw' -1 1
-subplot 1 1 0 '<>':title 'Earth in 3D':rotate 40 60
-copy phi dat 'pi*x':copy tet dat 'pi*y/2'
-copy x cos(tet)*cos(phi)
-copy y cos(tet)*sin(phi)
-copy z sin(tet)
-
-light on
-surfc x y z dat 'BbGYw'
-contp [-0.51,-0.51] x y z dat 'y'
-
Function error draw error boxes around the points. You can draw default boxes or semi-transparent symbol (like marker, see Line styles). Also you can set individual color for each box. See also error2 sample.
-
new a 100 100 'x^2*y':new b 100 100
-export a 'test_data.png' 'BbcyrR' -1 1
-import b 'test_data.png' 'BbcyrR' -1 1
-subplot 2 1 0 '':title 'initial':box:dens a
-subplot 2 1 1 '':title 'imported':box:dens b
-
Function fall draw waterfall surface. You can use meshnum for changing number of lines to be drawn. Also you can use ‘x’ style for drawing lines in other direction.
-
-
MGL code:
-
call 'prepare2d'
-title 'Fall plot':rotate 50 60:box:fall a
-
new dat 100 '0.4*rnd+0.1+sin(2*pi*x)'
-new in 100 '0.3+sin(2*pi*x)'
-list ini 1 1 3:fit res dat 'a+b*sin(c*x)' 'abc' ini
-title 'Fitting sample':yrange -2 2:box:axis:plot dat 'k. '
-plot res 'r':plot in 'b'
-text -0.9 -1.3 'fitted:' 'r:L'
-putsfit 0 -1.8 'y = ' 'r':text 0 2.2 'initial: y = 0.3+sin(2\pi x)' 'b'
-
Function flame2d generate points for flame fractals in 2d case.
-
-
MGL code:
-
list A [0.33,0,0,0.33,0,0,0.2] [0.33,0,0,0.33,0.67,0,0.2] [0.33,0,0,0.33,0.33,0.33,0.2]\
- [0.33,0,0,0.33,0,0.67,0.2] [0.33,0,0,0.33,0.67,0.67,0.2]
-new B 2 3 A.ny '0.3'
-put B 3 0 0 -1
-put B 3 0 1 -1
-put B 3 0 2 -1
-flame2d fx fy A B 1000000
-subplot 1 1 0 '<_':title 'Flame2d sample'
-ranges fx fy:box:axis
-plot fx fy 'r#o ';size 0.05
-
Function flow is another standard way to visualize vector fields – it draw lines (threads) which is tangent to local vector field direction. MathGL draw threads from edges of bounding box and from central slices. Sometimes it is not most appropriate variant – you may want to use flowp to specify manual position of threads. The color scheme is used for coloring (see Color scheme). At this warm color corresponds to normal flow (like attractor), cold one corresponds to inverse flow (like source).
-
-
MGL code:
-
call 'prepare2v'
-call 'prepare3v'
-subplot 2 2 0 '':title 'Flow plot (default)':box:flow a b
-subplot 2 2 1 '':title '"v" style':box:flow a b 'v'
-subplot 2 2 2 '':title '"#" and "." styles':box:flow a b '#':flow a b '.2k'
-subplot 2 2 3:title '3d variant':rotate 50 60:box:flow ex ey ez
-
Function flow3 draw flow threads, which start from given plane.
-
-
MGL code:
-
call 'prepare3v'
-subplot 2 2 0:title 'Flow3 plot (default)':rotate 50 60:box
-flow3 ex ey ez
-subplot 2 2 1:title '"v" style, from boundary':rotate 50 60:box
-flow3 ex ey ez 'v' 0
-subplot 2 2 2:title '"t" style':rotate 50 60:box
-flow3 ex ey ez 't' 0
-subplot 2 2 3:title 'from \i z planes':rotate 50 60:box
-flow3 ex ey ez 'z' 0
-flow3 ex ey ez 'z' 9
-
subplot 1 1 0 '':title 'SubData vs Evaluate'
-new in 9 'x^3/1.1':plot in 'ko ':box
-new arg 99 '4*x+4'
-evaluate e in arg off:plot e 'b.'; legend 'Evaluate'
-subdata s in arg:plot s 'r.';legend 'SubData'
-legend 2
-
-
C++ code:
-
void smgl_indirect(mglGraph *gr)
-{
- gr->SubPlot(1,1,0,""); gr->Title("SubData vs Evaluate");
- mglData in(9), arg(99), e, s;
- gr->Fill(in,"x^3/1.1"); gr->Fill(arg,"4*x+4");
- gr->Plot(in,"ko "); gr->Box();
- e = in.Evaluate(arg,false); gr->Plot(e,"b.","legend 'Evaluate'");
- s = in.SubData(arg); gr->Plot(s,"r.","legend 'SubData'");
- gr->Legend(2);
-}
-
Function ohlc draw Open-High-Low-Close diagram. This diagram show vertical line for between maximal(high) and minimal(low) values, as well as horizontal lines before/after vertical line for initial(open)/final(close) values of some process.
-
-
MGL code:
-
new o 10 '0.5*sin(pi*x)'
-new c 10 '0.5*sin(pi*(x+2/9))'
-new l 10 '0.3*rnd-0.8'
-new h 10 '0.3*rnd+0.5'
-subplot 1 1 0 '':title 'OHLC plot':box:ohlc o h l c
-
new x 100 'sin(pi*x)'
-new y 100 'cos(pi*x)'
-new z 100 'sin(2*pi*x)'
-new c 100 'cos(2*pi*x)'
-
-subplot 4 3 0:rotate 40 60:box:plot x y z
-subplot 4 3 1:rotate 40 60:box:area x y z
-subplot 4 3 2:rotate 40 60:box:tens x y z c
-subplot 4 3 3:rotate 40 60:box:bars x y z
-subplot 4 3 4:rotate 40 60:box:stem x y z
-subplot 4 3 5:rotate 40 60:box:textmark x y z c*2 '\alpha'
-subplot 4 3 6:rotate 40 60:box:tube x y z c/10
-subplot 4 3 7:rotate 40 60:box:mark x y z c 's'
-subplot 4 3 8:box:error x y z/10 c/10
-subplot 4 3 9:rotate 40 60:box:step x y z
-subplot 4 3 10:rotate 40 60:box:torus x z 'z';light on
-subplot 4 3 11:rotate 40 60:box:label x y z '%z'
-
new x 100 100 'sin(pi*(x+y)/2)*cos(pi*y/2)'
-new y 100 100 'cos(pi*(x+y)/2)*cos(pi*y/2)'
-new z 100 100 'sin(pi*y/2)'
-new c 100 100 'cos(pi*x)'
-
-subplot 4 4 0:rotate 40 60:box:surf x y z
-subplot 4 4 1:rotate 40 60:box:surfc x y z c
-subplot 4 4 2:rotate 40 60:box:surfa x y z c;alpha 1
-subplot 4 4 3:rotate 40 60:box:mesh x y z;meshnum 10
-subplot 4 4 4:rotate 40 60:box:tile x y z;meshnum 10
-subplot 4 4 5:rotate 40 60:box:tiles x y z c;meshnum 10
-subplot 4 4 6:rotate 40 60:box:axial x y z;alpha 0.5;light on
-subplot 4 4 7:rotate 40 60:box:cont x y z
-subplot 4 4 8:rotate 40 60:box:contf x y z;light on:contv x y z;light on
-subplot 4 4 9:rotate 40 60:box:belt x y z 'x';meshnum 10;light on
-subplot 4 4 10:rotate 40 60:box:dens x y z;alpha 0.5
-subplot 4 4 11:rotate 40 60:box
-fall x y z 'g';meshnum 10:fall x y z 'rx';meshnum 10
-subplot 4 4 12:rotate 40 60:box:belt x y z '';meshnum 10;light on
-subplot 4 4 13:rotate 40 60:box:boxs x y z '';meshnum 10;light on
-subplot 4 4 14:rotate 40 60:box:boxs x y z '#';meshnum 10;light on
-subplot 4 4 15:rotate 40 60:box:boxs x y z '@';meshnum 10;light on
-
new x 50 50 50 '(x+2)/3*sin(pi*y/2)'
-new y 50 50 50 '(x+2)/3*cos(pi*y/2)'
-new z 50 50 50 'z'
-new c 50 50 50 '-2*(x^2+y^2+z^4-z^2)+0.2'
-new d 50 50 50 '1-2*tanh(2*(x+y)^2)'
-
-alpha on:light on
-subplot 4 3 0:rotate 40 60:box:surf3 x y z c
-subplot 4 3 1:rotate 40 60:box:surf3c x y z c d
-subplot 4 3 2:rotate 40 60:box:surf3a x y z c d
-subplot 4 3 3:rotate 40 60:box:cloud x y z c
-subplot 4 3 4:rotate 40 60:box:cont3 x y z c:cont3 x y z c 'x':cont3 x y z c 'z'
-subplot 4 3 5:rotate 40 60:box:contf3 x y z c:contf3 x y z c 'x':contf3 x y z c 'z'
-subplot 4 3 6:rotate 40 60:box:dens3 x y z c:dens3 x y z c 'x':dens3 x y z c 'z'
-subplot 4 3 7:rotate 40 60:box:dots x y z c;meshnum 15
-subplot 4 3 8:rotate 40 60:box:densx c '' 0:densy c '' 0:densz c '' 0
-subplot 4 3 9:rotate 40 60:box:contx c '' 0:conty c '' 0:contz c '' 0
-subplot 4 3 10:rotate 40 60:box:contfx c '' 0:contfy c '' 0:contfz c '' 0
-
new x 20 20 20 '(x+2)/3*sin(pi*y/2)'
-new y 20 20 20 '(x+2)/3*cos(pi*y/2)'
-new z 20 20 20 'z+x'
-new ex 20 20 20 'x'
-new ey 20 20 20 'x^2+y'
-new ez 20 20 20 'y^2+z'
-
-new x1 50 50 '(x+2)/3*sin(pi*y/2)'
-new y1 50 50 '(x+2)/3*cos(pi*y/2)'
-new e1 50 50 'x'
-new e2 50 50 'x^2+y'
-
-subplot 3 3 0:rotate 40 60:box:vect x1 y1 e1 e2
-subplot 3 3 1:rotate 40 60:box:flow x1 y1 e1 e2
-subplot 3 3 2:rotate 40 60:box:pipe x1 y1 e1 e2
-subplot 3 3 3:rotate 40 60:box:dew x1 y1 e1 e2
-subplot 3 3 4:rotate 40 60:box:vect x y z ex ey ez
-subplot 3 3 5:rotate 40 60:box
-vect3 x y z ex ey ez:vect3 x y z ex ey ez 'x':vect3 x y z ex ey ez 'z'
-grid3 x y z z '{r9}':grid3 x y z z '{g9}x':grid3 x y z z '{b9}z'
-subplot 3 3 6:rotate 40 60:box:flow x y z ex ey ez
-subplot 3 3 7:rotate 40 60:box:pipe x y z ex ey ez
-
new re 128 'exp(-48*(x+0.7)^2)':new im 128
-pde a 'p^2+q^2-x-1+i*0.5*(z+x)*(z>-x)' re im 0.01 30
-transpose a
-subplot 1 1 0 '<_':title 'PDE solver'
-axis:xlabel '\i x':ylabel '\i z'
-crange 0 1:dens a 'wyrRk'
-fplot '-x' 'k|'
-text 0 0.95 'Equation: ik_0\partial_zu + \Delta u + x\cdot u + i \frac{x+z}{2}\cdot u = 0\n{}absorption: (x+z)/2 for x+z>0'
-
-
C++ code:
-
void smgl_pde(mglGraph *gr) // PDE sample
-{
- mglData a,re(128),im(128);
- gr->Fill(re,"exp(-48*(x+0.7)^2)");
- a = gr->PDE("p^2+q^2-x-1+i*0.5*(z+x)*(z>-x)", re, im, 0.01, 30);
- a.Transpose("yxz");
- if(big!=3) {gr->SubPlot(1,1,0,"<_"); gr->Title("PDE solver"); }
- gr->SetRange('c',0,1); gr->Dens(a,"wyrRk");
- gr->Axis(); gr->Label('x', "\\i x"); gr->Label('y', "\\i z");
- gr->FPlot("-x", "k|");
- gr->Puts(mglPoint(0, 0.95), "Equation: ik_0\\partial_zu + \\Delta u + x\\cdot u + i \\frac{x+z}{2}\\cdot u = 0\nabsorption: (x+z)/2 for x+z>0");
-}
-
Function pipe is similar to flow but draw pipes (tubes) which radius is proportional to the amplitude of vector field. The color scheme is used for coloring (see Color scheme). At this warm color corresponds to normal flow (like attractor), cold one corresponds to inverse flow (like source).
-
-
MGL code:
-
call 'prepare2v'
-call 'prepare3v'
-subplot 2 2 0 '':title 'Pipe plot (default)':light on:box:pipe a b
-subplot 2 2 1 '':title '"i" style':box:pipe a b 'i'
-subplot 2 2 2 '':title 'from edges only':box:pipe a b '#'
-subplot 2 2 3:title '3d variant':rotate 50 60:box:pipe ex ey ez '' 0.1
-
Function plot is most standard way to visualize 1D data array. By default, Plot use colors from palette. However, you can specify manual color/palette, and even set to use new color for each points by using ‘!’ style. Another feature is ‘’ style which draw only markers without line between points.
-
Function pmap draw Poincare map – show intersections of the curve and the surface.
-
-
MGL code:
-
subplot 1 1 0 '<_^':title 'Poincare map sample'
-ode r 'cos(y)+sin(z);cos(z)+sin(x);cos(x)+sin(y)' 'xyz' [0.1,0,0] 0.1 100
-rotate 40 60:copy x r(0):copy y r(1):copy z r(2)
-ranges x y z
-axis:plot x y z 'b'
-xlabel '\i x' 0:ylabel '\i y' 0:zlabel '\i z'
-pmap x y z z 'b#o'
-fsurf '0'
-
ranges 0 1 0 1 0 1
-new x 50 '0.25*(1+cos(2*pi*x))'
-new y 50 '0.25*(1+sin(2*pi*x))'
-new z 50 'x'
-new a 20 30 '30*x*y*(1-x-y)^2*(x+y<1)'
-new rx 10 'rnd':new ry 10:fill ry '(1-v)*rnd' rx
-light on
-
-title 'Projection sample':ternary 4:rotate 50 60
-box:axis:grid
-plot x y z 'r2':surf a '#'
-xlabel 'X':ylabel 'Y':zlabel 'Z'
-
The radar plot is variant of plot, which make plot in polar coordinates and draw radial rays in point directions. If you just need a plot in polar coordinates then I recommend to use Curvilinear coordinates or plot in parametric form with x=r*cos(fi); y=r*sin(fi);.
-
-
MGL code:
-
new yr 10 3 '0.4*sin(pi*(x+1.5+y/2)+0.1*rnd)'
-subplot 1 1 0 '':title 'Radar plot (with grid, "\#")':radar yr '#'
-
new x 10 '0.5+rnd':cumsum x 'x':norm x -1 1
-copy y sin(pi*x)/1.5
-subplot 2 2 0 '<_':title 'Refill sample'
-box:axis:plot x y 'o ':fplot 'sin(pi*x)/1.5' 'B:'
-new r 100:refill r x y:plot r 'r'
-
-subplot 2 2 1 '<_':title 'Global spline'
-box:axis:plot x y 'o ':fplot 'sin(pi*x)/1.5' 'B:'
-new r 100:gspline r x y:plot r 'r'
-
-new y 10 '0.5+rnd':cumsum y 'x':norm y -1 1
-copy xx x:extend xx 10
-copy yy y:extend yy 10:transpose yy
-copy z sin(pi*xx*yy)/1.5
-alpha on:light on
-subplot 2 2 2:title '2d regular':rotate 40 60
-box:axis:mesh xx yy z 'k'
-new rr 100 100:refill rr x y z:surf rr
-
-new xx 10 10 '(x+1)/2*cos(y*pi/2-1)':new yy 10 10 '(x+1)/2*sin(y*pi/2-1)'
-copy z sin(pi*xx*yy)/1.5
-subplot 2 2 3:title '2d non-regular':rotate 40 60
-box:axis:plot xx yy z 'ko '
-new rr 100 100:refill rr xx yy z:surf rr
-
Function region fill the area between 2 curves. It support gradient filling if 2 colors per curve is specified. Also it can fill only the region y1<y<y2 if style ‘i’ is used.
-
zrange 0 1
-new x 20 30 '(x+2)/3*cos(pi*y)'
-new y 20 30 '(x+2)/3*sin(pi*y)'
-new z 20 30 'exp(-6*x^2-2*sin(pi*y)^2)'
-
-subplot 2 1 0:title 'Cartesian space':rotate 30 -40
-axis 'xyzU':box
-xlabel 'x':ylabel 'y'
-origin 1 1:grid 'xy'
-mesh x y z
-
-# section along 'x' direction
-solve u x 0.5 'x'
-var v u.nx 0 1
-evaluate yy y u v
-evaluate xx x u v
-evaluate zz z u v
-plot xx yy zz 'k2o'
-
-# 1st section along 'y' direction
-solve u1 x -0.5 'y'
-var v1 u1.nx 0 1
-evaluate yy y v1 u1
-evaluate xx x v1 u1
-evaluate zz z v1 u1
-plot xx yy zz 'b2^'
-
-# 2nd section along 'y' direction
-solve u2 x -0.5 'y' u1
-evaluate yy y v1 u2
-evaluate xx x v1 u2
-evaluate zz z v1 u2
-plot xx yy zz 'r2v'
-
-subplot 2 1 1:title 'Accompanied space'
-ranges 0 1 0 1:origin 0 0
-axis:box:xlabel 'i':ylabel 'j':grid2 z 'h'
-
-plot u v 'k2o':line 0.4 0.5 0.8 0.5 'kA'
-plot v1 u1 'b2^':line 0.5 0.15 0.5 0.3 'bA'
-plot v1 u2 'r2v':line 0.5 0.7 0.5 0.85 'rA'
-
Function surf is most standard way to visualize 2D data array. Surf use color scheme for coloring (see Color scheme). You can use ‘#’ style for drawing black meshes on the surface.
-
-
MGL code:
-
call 'prepare2d'
-subplot 2 2 0:title 'Surf plot (default)':rotate 50 60:light on:box:surf a
-subplot 2 2 1:title '"\#" style; meshnum 10':rotate 50 60:box:surf a '#'; meshnum 10
-subplot 2 2 2:title '"." style':rotate 50 60:box:surf a '.'
-new x 50 40 '0.8*sin(pi*x)*sin(pi*(y+1)/2)'
-new y 50 40 '0.8*cos(pi*x)*sin(pi*(y+1)/2)'
-new z 50 40 '0.8*cos(pi*(y+1)/2)'
-subplot 2 2 3:title 'parametric form':rotate 50 60:box:surf x y z 'BbwrR'
-
Function surf3 is one of most suitable (for my opinion) functions to visualize 3D data. It draw the isosurface(s) – surface(s) of constant amplitude (3D analogue of contour lines). You can draw wired isosurfaces if specify ‘#’ style.
-
-
MGL code:
-
call 'prepare3d'
-light on:alpha on
-subplot 2 2 0:title 'Surf3 plot (default)'
-rotate 50 60:box:surf3 c
-subplot 2 2 1:title '"\#" style'
-rotate 50 60:box:surf3 c '#'
-subplot 2 2 2:title '"." style'
-rotate 50 60:box:surf3 c '.'
-
call 'prepare1d'
-subplot 1 3 0 '':box:plot y(:,0)
-text y 'This is very very long string drawn along a curve' 'k'
-text y 'Another string drawn under a curve' 'Tr'
-subplot 1 3 1 '':box:plot y(:,0)
-text y 'This is very very long string drawn along a curve' 'k:C'
-text y 'Another string drawn under a curve' 'Tr:C'
-subplot 1 3 2 '':box:plot y(:,0)
-text y 'This is very very long string drawn along a curve' 'k:R'
-text y 'Another string drawn under a curve' 'Tr:R'
-
-
C++ code:
-
void smgl_text2(mglGraph *gr) // text drawing
-{
- mglData y; mgls_prepare1d(&y);
- if(big!=3) gr->SubPlot(1,3,0,"");
- gr->Box(); gr->Plot(y.SubData(-1,0));
- gr->Text(y,"This is very very long string drawn along a curve","k");
- gr->Text(y,"Another string drawn under a curve","Tr");
- if(big==3) return;
-
- gr->SubPlot(1,3,1,"");
- gr->Box(); gr->Plot(y.SubData(-1,0));
- gr->Text(y,"This is very very long string drawn along a curve","k:C");
- gr->Text(y,"Another string drawn under a curve","Tr:C");
-
- gr->SubPlot(1,3,2,"");
- gr->Box(); gr->Plot(y.SubData(-1,0));
- gr->Text(y,"This is very very long string drawn along a curve","k:R");
- gr->Text(y,"Another string drawn under a curve","Tr:R");
-}
-
Example of use triangulate for arbitrary placed points.
-
-
MGL code:
-
new x 100 '2*rnd-1':new y 100 '2*rnd-1':copy z x^2-y^2
-new g 30 30:triangulate d x y
-title 'Triangulation'
-rotate 50 60:box:light on
-triplot d x y z:triplot d x y z '#k'
-datagrid g x y z:mesh g 'm'
-
Functions triplot and quadplot draw set of triangles (or quadrangles, correspondingly) for irregular data arrays. Note, that you have to provide not only vertexes, but also the indexes of triangles or quadrangles. I.e. perform triangulation by some other library. See also triangulate.
-
Function vect is most standard way to visualize vector fields – it draw a lot of arrows or hachures for each data cell. It have a lot of options which can be seen on the figure (and in the sample code), and use color scheme for coloring (see Color scheme).
-
-
MGL code:
-
call 'prepare2v'
-call 'prepare3v'
-subplot 3 2 0 '':title 'Vect plot (default)':box:vect a b
-subplot 3 2 1 '':title '"." style; "=" style':box:vect a b '.='
-subplot 3 2 2 '':title '"f" style':box:vect a b 'f'
-subplot 3 2 3 '':title '">" style':box:vect a b '>'
-subplot 3 2 4 '':title '"<" style':box:vect a b '<'
-subplot 3 2 5:title '3d variant':rotate 50 60:box:vect ex ey ez
-
Function vect3 draw ordinary vector field plot but at slices of 3D data.
-
-
MGL code:
-
call 'prepare3v'
-subplot 2 1 0:title 'Vect3 sample':rotate 50 60
-origin 0 0 0:box:axis '_xyz'
-vect3 ex ey ez 'x':vect3 ex ey ez:vect3 ex ey ez 'z'
-subplot 2 1 1:title '"f" style':rotate 50 60
-origin 0 0 0:box:axis '_xyz'
-vect3 ex ey ez 'fx':vect3 ex ey ez 'f':vect3 ex ey ez 'fz'
-grid3 ex 'Wx':grid3 ex 'W':grid3 ex 'Wz'
-
list x -0.3 0 0.3:list y 0.3 -0.3 0.3:list e 0.7 0.7 0.7
-subplot 1 1 0:title 'Venn-like diagram'
-transptype 1:alpha on:error x y e e '!rgb@#o';alpha 0.1
-
This appendix contain the full list of symbols (characters) used by MathGL for setting up plot. Also it contain sections for full list of hot-keys supported by mglview tool and by UDAV program.
-
Create new window with empty script. Note, all scripts share variables. So, second window can be used to see some additional information of existed variables.
-
Ctrl-O
Open and execute/show script or data from file. You may switch off automatic exection in UDAV properties
-
Ctrl-S
Save script to a file.
-
Ctrl-P
Open printer dialog and print graphics.
-
Ctrl-Z
Undo changes in script editor.
-
Ctrl-Shift-Z
Redo changes in script editor.
-
Ctrl-X
Cut selected text into clipboard.
-
Ctrl-C
Copy selected text into clipboard.
-
Ctrl-V
Paste selected text from clipboard.
-
Ctrl-A
Select all text in editor.
-
Ctrl-F
Show dialog for text finding.
-
F3
Find next occurrence of the text.
-
Win-C or Meta-C
Show dialog for new command and put it into the script.
-
Win-F or Meta-F
Insert last fitted formula with found coefficients.
-
Win-S or Meta-S
Show dialog for styles and put it into the script. Styles define the plot view (color scheme, marks, dashing and so on).
-
Win-O or Meta-O
Show dialog for options and put it into the script. Options are used for additional setup the plot.
-
Win-N or Meta-N
Replace selected expression by its numerical value.
-
Win-P or Meta-P
Select file and insert its file name into the script.
-
Win-G or Meta-G
Show dialog for plot setup and put resulting code into the script. This dialog setup axis, labels, lighting and other general things.
-
Ctrl-Shift-O
Load data from file. Data will be deleted only at exit but UDAV will not ask to save it.
-
Ctrl-Shift-S
Save data to a file.
-
Ctrl-Shift-C
Copy range of numbers to clipboard.
-
Ctrl-Shift-V
Paste range of numbers from clipboard.
-
Ctrl-Shift-N
Recreate the data with new sizes and fill it by zeros.
-
Ctrl-Shift-R
Resize (interpolate) the data to specified sizes.
-
Ctrl-Shift-T
Transform data along dimension(s).
-
Ctrl-Shift-M
Make another data.
-
Ctrl-Shift-H
Find histogram of data.
-
Ctrl-T
Switch on/off transparency for the graphics.
-
Ctrl-L
Switch on/off additional lightning for the graphics.
-
Ctrl-G
Switch on/off grid of absolute coordinates.
-
Ctrl-Space
Restore default graphics rotation, zoom and perspective.
-
F5
Execute script and redraw graphics.
-
F6
Change canvas size to fill whole region.
-
F7
Stop script execution and drawing.
-
F8
Show/hide tool window with list of hidden plots.
-
F9
Restore status for ’once’ command and reload data.
-
Ctrl-F5
Run slideshow. If no parameter specified then the dialog with slideshow options will appear.
-
Ctrl-Comma, Ctrl-Period
Show next/previous slide. If no parameter specified then the dialog with slideshow options will appear.
-
Ctrl-W
Open dialog with slideshow options.
-
Ctrl-Shift-G
Copy graphics to clipboard.
-
F1
Show help on MGL commands
-
F2
Show/hide tool window with messages and information.
-
F4
Show/hide calculator which evaluate and help to type textual formulas. Textual formulas may contain data variables too.
Starting from v.1.6 the MathGL library uses new font files. The font is defined in 4 files with suffixes ‘*.vfm’, ‘*_b.vfm’, ‘*_i.vfm’, ‘*_bi.vfm’. These files are text files containing the data for roman font, bold font, italic font and bold italic font. The files (or some symbols in the files) for bold, italic or bold italic fonts can be absent. In this case the roman glyph will be used for them. By analogy, if the bold italic font is absent but the bold font is present then bold glyph will be used for bold italic. You may create these font files by yourself from *.ttf, *.otf files with the help of program font_tools. This program can be found at MathGL home site.
-
-
The format of font files (*.vfm – vector font for MathGL) is the following.
-
-
First string contains human readable comment and is always ignored.
-
Second string contains 3 numbers, delimited by space or tabulation. The order of numbers is the following: numg – the number of glyphs in the file (integer), fact – the factor for glyph sizing (mreal), size – the size of buffer for glyph description (integer).
-
After it numg-th strings with glyphs description are placed. Each string contains 6 positive numbers, delimited by space of tabulation. The order of numbers is the following: Unicode glyph ID, glyph width, number of lines in glyph, position of lines coordinates in the buffer (length is 2*number of lines), number of triangles in glyph, position of triangles coordinates in the buffer (length is 6*number of triangles).
-
The end of file contains the buffer with point coordinates at lines or triangles vertexes. The size of buffer (the number of integer) is size.
-
-
-
Each font file can be compressed by gzip.
-
-
Note: the closing contour line is done automatically (so the last segment may be absent). For starting new contour use a point with coordinates {0x3fff, 0x3fff}.
-
MGLD is textual file, which contain all required information for drawing 3D image, i.e. it contain vertexes with colors and normales, primitives with all properties, textures, and glyph descriptions. MGLD file can be imported or viewed separately, without parsing data files itself.
-
which contain signature ‘MGLD’ and number of points npnts, number of primitives nprim, number of textures ntxtr, number of glyph descriptions nglfs, and optional description. Empty strings and string with ‘#’ are ignored.
-
-
Next, file contain npnts strings with points coordinates and colors. The format of each string is
-
x y z c t ta u v w r g b a
-
Here x, y, z are coordinates, c, t are color indexes in texture, ta is normalized t according to current alpha setting, u, v, w are coordinates of normal vector (can be NAN if disabled), r, g, b, a are RGBA color values.
-
-
Next, file contain nprim strings with properties of primitives. The format of each string is
-
type n1 n2 n3 n4 id s w p
-
Here type is kind of primitive (0 - mark, 1 - line, 2 - triangle, 3 - quadrangle, 4 - glyph), n1...n4 is index of point for vertexes, id is primitive identification number, s and w are size and width if applicable, p is scaling factor for glyphs.
-
-
Next, file contain ntxtr strings with descriptions of textures. The format of each string is
-
smooth alpha colors
-
Here smooth set to enable smoothing between colors, alpha set to use half-transparent texture, colors contain color scheme itself as it described in Color scheme.
-
-
Finally, file contain nglfs entries with description of each glyph used in the figure. The format of entries are
-
nT nL
-xA yA xB yB xC yC ...
-xP yP ...
-
Here nT is the number of triangles; nL is the number of line vertexes; xA, yA, xB, yB, xC, yC are coordinates of triangles; and xP, yP, xQ, yQ are coordinates of lines. Line coordinate xP=0x3fff, yP=0x3fff denote line breaking.
-
MathGL can save points and primitives of 3D object. It contain a set of variables listed below.
-
-
-
‘width’
-
width of the image;
-
-
‘height’
-
height of the image
-
-
‘depth’
-
depth of the image, usually =sqrt(width*height);
-
-
-
‘npnts’
-
number of points (vertexes);
-
-
‘pnts’
-
array of coordinates of points (vertexes), each element is array in form [x, y, z];
-
-
-
‘nprim’
-
number of primitives;
-
-
‘prim’
-
array of primitives, each element is array in form [type, n1, n2, n3, n4, id, s, w, p, z, color].
-
-
Here type is kind of primitive (0 - mark, 1 - line, 2 - triangle, 3 - quadrangle, 4 - glyph), n1...n4 is index of point for vertexes and n2 can be index of glyph coordinate, s and w are size and width if applicable, z is average z-coordinate, id is primitive identification number, p is scaling factor for glyphs.
-
-
-
‘ncoor’
-
number of glyph positions
-
-
‘coor’
-
array of glyph positions, each element is array in form [dx,dy]
-
-
-
‘nglfs’
-
number of glyph descriptions
-
-
‘glfs’
-
array of glyph descriptions, each element is array in form [nL, [xP0, yP0, xP1, yP1 ...]]. Here nL is the number of line vertexes; and xP, yP, xQ, yQ are coordinates of lines. Line coordinate xP=0x3fff, yP=0x3fff denote line breaking.
-
MathGL can read IFS fractal parameters (see ifsfile) from a IFS file. Let remind IFS file format. File may contain several records. Each record contain the name of fractal (‘binary’ in the example below) and the body of fractal, which is enclosed in curly braces {}. Symbol ‘;’ start the comment. If the name of fractal contain ‘(3D)’ or ‘(3d)’ then the 3d IFS fractal is specified. The sample below contain two fractals: ‘binary’ – usual 2d fractal, and ‘3dfern (3D)’ – 3d fractal.
-
Table below show plotting time in seconds for all samples in file examples/samples.cpp. The test was done in my laptop (i5-2430M) with 64-bit Debian.
-
-
Few words about the speed. Firstly, direct bitmap drawing (Quality=4,5,6) is faster than buffered one (Quality=0,1,2), but sometimes it give incorrect result (see cloud) and don’t allow to export in vector or 3d formats (like EPS, SVG, PDF ...). Secondly, lower quality is faster than high one generally, i.e. Quality=1 is faster than Quality=2, and Quality=0 is faster than Quality=1. However, if plot contain a lot of faces (like cloud, surf3, pipe, dew) then Quality=0 may become slow, especially for small images. Finally, smaller images are drawn faster than larger ones.
-
-
Results for image size 800*600 (default one).
-
-
Name
q=0
q=1
q=2
q=4
q=5
q=6
q=8
-
3wave
0.0322
0.0627
0.0721
0.0425
0.11
0.136
0.0271
-
alpha
0.0892
0.108
0.113
0.0473
0.124
0.145
0.0297
-
apde
48.2
47.4
47.6
47.4
47.8
48.4
47.9
-
area
0.0376
0.0728
0.0752
0.033
0.141
0.165
0.0186
-
aspect
0.0442
0.0572
0.0551
0.031
0.0999
0.103
0.0146
-
axial
0.639
0.917
0.926
0.195
0.525
0.552
0.119
-
axis
0.0683
0.107
0.108
0.0466
0.196
0.202
0.0169
-
barh
0.0285
0.0547
0.0603
0.0292
0.101
0.115
0.0114
-
bars
0.0414
0.0703
0.0843
0.1
0.185
0.184
0.0295
-
belt
0.0286
0.0532
0.0577
0.0384
0.0735
0.1
0.0131
-
bifurcation
0.589
0.635
0.609
0.531
0.572
0.579
0.512
-
box
0.0682
0.0805
0.0828
0.0314
0.124
0.121
0.0169
-
boxplot
0.0102
0.0317
0.0347
0.02
0.0499
0.0554
0.0167
-
boxs
0.239
0.363
0.4
0.0798
0.216
0.234
0.0721
-
candle
0.0286
0.0549
0.053
0.0263
0.0483
0.0564
0.0109
-
chart
0.416
0.613
0.707
0.26
1.07
1.59
0.191
-
cloud
0.0312
4.15
4.11
0.0306
0.715
0.924
0.0168
-
colorbar
0.108
0.172
0.177
0.0787
0.258
0.266
0.0452
-
combined
0.36
0.336
0.332
0.198
0.316
0.33
0.196
-
cones
0.145
0.139
0.14
0.0937
0.248
0.276
0.0363
-
cont
0.0987
0.141
0.141
0.0585
0.207
0.194
0.0455
-
cont3
0.0323
0.058
0.0587
0.0304
0.0726
0.0837
0.0162
-
cont_xyz
0.0417
0.0585
0.0612
0.0417
0.0833
0.0845
0.0294
-
contd
0.191
0.245
0.236
0.104
0.189
0.201
0.0902
-
contf
0.162
0.179
0.182
0.0789
0.166
0.177
0.067
-
contf3
0.123
0.12
0.134
0.065
0.123
0.155
0.0538
-
contf_xyz
0.0751
0.0922
0.111
0.0756
0.0879
0.0956
0.0462
-
contv
0.0947
0.123
0.136
0.0757
0.163
0.18
0.0469
-
correl
0.0339
0.0629
0.0599
0.0288
0.115
0.138
0.0165
-
curvcoor
0.112
0.164
0.171
0.0864
0.296
0.298
0.0739
-
cut
0.695
0.465
0.484
0.303
0.385
0.371
0.316
-
dat_diff
0.0457
0.079
0.0825
0.0346
0.136
0.158
0.0186
-
dat_extra
0.175
0.181
0.173
0.0877
0.163
0.173
0.0463
-
data1
2.39
1.76
1.75
1.33
1.38
1.37
1.4
-
data2
1.42
1.26
1.28
1.17
1.24
1.29
1.14
-
dens
0.0867
0.122
0.131
0.0615
0.145
0.168
0.032
-
dens3
0.0722
0.0769
0.0937
0.0437
0.0947
0.151
0.0797
-
dens_xyz
0.0599
0.0875
0.0961
0.0463
0.089
0.0897
0.0315
-
detect
0.133
0.151
0.176
0.0861
0.116
0.138
0.0721
-
dew
1.48
1.07
0.971
0.473
0.537
0.416
0.195
-
diffract
0.0878
0.127
0.139
0.0607
0.219
0.237
0.0274
-
dilate
0.0778
0.128
0.138
0.0592
0.242
0.232
0.0298
-
dots
0.0685
0.1
0.101
0.0694
0.134
0.129
0.0261
-
earth
0.0147
0.033
0.0218
0.0168
0.0168
0.0191
0.00177
-
error
0.0312
0.0707
0.0709
0.0288
0.135
0.137
0.016
-
error2
0.0581
0.0964
0.0958
0.0595
0.173
0.187
0.0444
-
export
0.116
0.158
0.167
0.0799
0.132
0.133
0.0685
-
fall
0.035
0.051
0.0577
0.018
0.0585
0.0709
0.0142
-
fexport
1.52
1.76
1.78
0.278
0.604
0.606
1.35
-
fit
0.0371
0.0653
0.0666
0.0277
0.081
0.0837
0.014
-
flame2d
5.37
5.54
5.5
3.04
3.21
3.09
1.13
-
flow
0.368
0.451
0.444
0.36
0.5
0.48
0.352
-
fog
0.0406
0.0645
0.0688
0.0379
0.0793
0.0894
0.0156
-
fonts
0.0477
0.0926
0.112
0.0347
0.0518
0.0519
0.0413
-
grad
0.0607
0.104
0.129
0.0715
0.103
0.12
0.0633
-
hist
0.125
0.148
0.159
0.0919
0.116
0.129
0.0372
-
ifs2d
0.594
0.623
0.62
0.315
0.349
0.33
0.109
-
ifs3d
0.787
0.777
0.784
0.294
0.353
0.366
0.117
-
indirect
0.0286
0.0517
0.0543
0.031
0.0612
0.104
0.0144
-
inplot
0.0687
0.0979
0.0993
0.0622
0.181
0.195
0.0444
-
iris
0.00846
0.025
0.0198
0.00349
0.0172
0.0182
0.0018
-
label
0.0285
0.045
0.058
0.0267
0.0525
0.0618
0.014
-
lamerey
0.0305
0.0372
0.0455
0.019
0.0604
0.0633
0.0024
-
legend
0.0764
0.202
0.207
0.0455
0.138
0.148
0.0162
-
light
0.0903
0.129
0.122
0.0573
0.132
0.144
0.021
-
loglog
0.103
0.168
0.16
0.0806
0.228
0.235
0.0802
-
map
0.0303
0.0653
0.0721
0.0337
0.0821
0.0866
0.015
-
mark
0.0191
0.0324
0.0368
0.0261
0.0533
0.045
0.0072
-
mask
0.0442
0.0964
0.101
0.0343
0.205
0.211
0.0115
-
mesh
0.034
0.0774
0.0682
0.0192
0.0765
0.0742
0.0145
-
mirror
0.092
0.128
0.142
0.0607
0.174
0.176
0.0312
-
molecule
0.0827
0.0842
0.0859
0.0443
0.0997
0.146
0.0115
-
ode
0.149
0.202
0.202
0.147
0.282
0.316
0.133
-
ohlc
0.0059
0.0278
0.0271
0.0152
0.0517
0.045
0.0152
-
param1
0.161
0.252
0.26
0.0941
0.301
0.341
0.0466
-
param2
0.535
0.58
0.539
0.26
0.452
0.475
0.189
-
param3
1.75
2.37
2.32
0.677
0.899
0.907
0.758
-
paramv
1.21
1.39
1.36
0.788
0.974
0.968
0.69
-
parser
0.0346
0.0582
0.0687
0.0317
0.108
0.11
0.0275
-
pde
0.329
0.358
0.373
0.272
0.311
0.364
0.264
-
pendelta
0.0653
0.0525
0.0648
0.0517
0.0531
0.0522
0.0653
-
pipe
0.598
0.737
0.738
0.382
0.493
0.505
0.34
-
plot
0.0397
0.0642
0.114
0.0444
0.123
0.118
0.0194
-
pmap
0.0913
0.115
0.125
0.0572
0.0999
0.113
0.0469
-
primitives
0.0581
0.108
0.128
0.0649
0.181
0.21
0.00928
-
projection
0.13
0.264
0.286
0.0704
0.351
0.349
0.0683
-
projection5
0.117
0.207
0.215
0.0717
0.3
0.312
0.0437
-
pulse
0.0273
0.0395
0.0413
0.0183
0.0576
0.0635
0.0023
-
qo2d
0.218
0.246
0.274
0.198
0.243
0.255
0.177
-
quality0
0.0859
0.0902
0.087
0.0808
0.0808
0.0823
0.0796
-
quality1
0.189
0.166
0.171
0.175
0.17
0.173
0.166
-
quality2
0.183
0.183
0.175
0.172
0.171
0.183
0.184
-
quality4
0.082
0.0713
0.0728
0.0636
0.0843
0.0651
0.0592
-
quality5
0.366
0.359
0.363
0.366
0.354
0.356
0.357
-
quality6
0.373
0.367
0.365
0.366
0.368
0.383
0.366
-
quality8
0.0193
0.019
0.0289
0.0298
0.0165
0.0244
0.0229
-
radar
0.0193
0.0369
0.0545
0.0158
0.0525
0.0532
0.0115
-
refill
0.153
0.168
0.166
0.0746
0.239
0.258
0.0467
-
region
0.0396
0.0723
0.0859
0.0342
0.133
0.159
0.017
-
scanfile
0.0315
0.036
0.0497
0.0169
0.0486
0.053
0.014
-
schemes
0.0703
0.114
0.117
0.062
0.204
0.21
0.019
-
section
0.0294
0.0483
0.054
0.0221
0.0804
0.0821
0.00568
-
several_light
0.0441
0.0541
0.0701
0.0299
0.0602
0.0815
0.0117
-
solve
0.0461
0.109
0.105
0.0462
0.18
0.191
0.0184
-
stem
0.0418
0.0599
0.0591
0.0308
0.126
0.139
0.015
-
step
0.0399
0.0614
0.0554
0.0315
0.0958
0.113
0.0145
-
stereo
0.0569
0.0652
0.0811
0.031
0.0807
0.093
0.0163
-
stfa
0.0425
0.117
0.111
0.0416
0.115
0.121
0.0157
-
style
0.0892
0.197
0.204
0.0596
0.349
0.369
0.0158
-
surf
0.109
0.133
0.157
0.0657
0.16
0.158
0.0315
-
surf3
1.79
2.6
2.57
0.949
2.36
2.44
0.625
-
surf3a
0.431
0.281
0.297
0.176
0.235
0.252
0.178
-
surf3c
0.423
0.285
0.301
0.175
0.202
0.265
0.177
-
surf3ca
0.428
0.303
0.31
0.176
0.203
0.265
0.19
-
surfa
0.0409
0.0577
0.0714
0.0265
0.062
0.0725
0.0154
-
surfc
0.0422
0.0453
0.058
0.0282
0.0628
0.0749
0.0161
-
surfca
0.0416
0.0598
0.058
0.0254
0.0541
0.0671
0.015
-
table
0.103
0.213
0.214
0.0484
0.112
0.117
0.0156
-
tape
0.0409
0.0784
0.0836
0.0347
0.124
0.138
0.0164
-
tens
0.0329
0.0485
0.0441
0.0279
0.0805
0.0757
0.00561
-
ternary
0.104
0.218
0.214
0.0634
0.393
0.425
0.0352
-
text
0.0827
0.156
0.15
0.0261
0.114
0.127
0.015
-
text2
0.0719
0.12
0.131
0.115
0.129
0.137
0.016
-
textmark
0.0403
0.0749
0.0788
0.0223
0.0607
0.0653
0.014
-
ticks
0.0868
0.193
0.195
0.0611
0.259
0.249
0.0275
-
tile
0.0349
0.0444
0.0597
0.0308
0.0546
0.0547
0.0111
-
tiles
0.0393
0.0585
0.0534
0.0205
0.0648
0.0597
0.0174
-
torus
0.114
0.197
0.193
0.0713
0.394
0.457
0.0306
-
traj
0.0251
0.0413
0.043
0.0178
0.0628
0.0968
0.0129
-
triangulation
0.0328
0.0659
0.0792
0.0319
0.0966
0.0888
0.0155
-
triplot
0.0302
0.0705
0.102
0.0198
0.0973
0.127
0.0143
-
tube
0.077
0.143
0.192
0.0593
0.191
0.21
0.0197
-
type0
0.177
0.172
0.198
0.0673
0.141
0.2
0.0576
-
type1
0.174
0.173
0.2
0.0648
0.153
0.17
0.0571
-
type2
0.188
0.198
0.197
0.0773
0.186
0.193
0.0647
-
vect
0.129
0.336
0.194
0.0608
0.174
0.177
0.043
-
vect3
0.0317
0.0781
0.0869
0.0366
0.155
0.159
0.0174
-
venn
0.0153
0.0503
0.0787
0.0115
0.0665
0.075
0.00249
-
-
-
Results for image size 1920*1440 (print quality)
-
The full list of TeX-like commands recognizable by MathGL is shown below. If command is not recognized then it will be printed as is by ommitting ‘\’ symbol. For example, ‘\#’ produce “#”, ‘\\’ produce “\”, ‘\qq’ produce “qq”.
-
The purpose of this License is to make a manual, textbook, or other
-functional and useful document free in the sense of freedom: to
-assure everyone the effective freedom to copy and redistribute it,
-with or without modifying it, either commercially or noncommercially.
-Secondarily, this License preserves for the author and publisher a way
-to get credit for their work, while not being considered responsible
-for modifications made by others.
-
-
This License is a kind of “copyleft”, which means that derivative
-works of the document must themselves be free in the same sense. It
-complements the GNU General Public License, which is a copyleft
-license designed for free software.
-
-
We have designed this License in order to use it for manuals for free
-software, because free software needs free documentation: a free
-program should come with manuals providing the same freedoms that the
-software does. But this License is not limited to software manuals;
-it can be used for any textual work, regardless of subject matter or
-whether it is published as a printed book. We recommend this License
-principally for works whose purpose is instruction or reference.
-
-
APPLICABILITY AND DEFINITIONS
-
-
This License applies to any manual or other work, in any medium, that
-contains a notice placed by the copyright holder saying it can be
-distributed under the terms of this License. Such a notice grants a
-world-wide, royalty-free license, unlimited in duration, to use that
-work under the conditions stated herein. The “Document”, below,
-refers to any such manual or work. Any member of the public is a
-licensee, and is addressed as “you”. You accept the license if you
-copy, modify or distribute the work in a way requiring permission
-under copyright law.
-
-
A “Modified Version” of the Document means any work containing the
-Document or a portion of it, either copied verbatim, or with
-modifications and/or translated into another language.
-
-
A “Secondary Section” is a named appendix or a front-matter section
-of the Document that deals exclusively with the relationship of the
-publishers or authors of the Document to the Document’s overall
-subject (or to related matters) and contains nothing that could fall
-directly within that overall subject. (Thus, if the Document is in
-part a textbook of mathematics, a Secondary Section may not explain
-any mathematics.) The relationship could be a matter of historical
-connection with the subject or with related matters, or of legal,
-commercial, philosophical, ethical or political position regarding
-them.
-
-
The “Invariant Sections” are certain Secondary Sections whose titles
-are designated, as being those of Invariant Sections, in the notice
-that says that the Document is released under this License. If a
-section does not fit the above definition of Secondary then it is not
-allowed to be designated as Invariant. The Document may contain zero
-Invariant Sections. If the Document does not identify any Invariant
-Sections then there are none.
-
-
The “Cover Texts” are certain short passages of text that are listed,
-as Front-Cover Texts or Back-Cover Texts, in the notice that says that
-the Document is released under this License. A Front-Cover Text may
-be at most 5 words, and a Back-Cover Text may be at most 25 words.
-
-
A “Transparent” copy of the Document means a machine-readable copy,
-represented in a format whose specification is available to the
-general public, that is suitable for revising the document
-straightforwardly with generic text editors or (for images composed of
-pixels) generic paint programs or (for drawings) some widely available
-drawing editor, and that is suitable for input to text formatters or
-for automatic translation to a variety of formats suitable for input
-to text formatters. A copy made in an otherwise Transparent file
-format whose markup, or absence of markup, has been arranged to thwart
-or discourage subsequent modification by readers is not Transparent.
-An image format is not Transparent if used for any substantial amount
-of text. A copy that is not “Transparent” is called “Opaque”.
-
-
Examples of suitable formats for Transparent copies include plain
-ASCII without markup, Texinfo input format, LaTeX input
-format, SGML or XML using a publicly available
-DTD, and standard-conforming simple HTML,
-PostScript or PDF designed for human modification. Examples
-of transparent image formats include PNG, XCF and
-JPG. Opaque formats include proprietary formats that can be
-read and edited only by proprietary word processors, SGML or
-XML for which the DTD and/or processing tools are
-not generally available, and the machine-generated HTML,
-PostScript or PDF produced by some word processors for
-output purposes only.
-
-
The “Title Page” means, for a printed book, the title page itself,
-plus such following pages as are needed to hold, legibly, the material
-this License requires to appear in the title page. For works in
-formats which do not have any title page as such, “Title Page” means
-the text near the most prominent appearance of the work’s title,
-preceding the beginning of the body of the text.
-
-
A section “Entitled XYZ” means a named subunit of the Document whose
-title either is precisely XYZ or contains XYZ in parentheses following
-text that translates XYZ in another language. (Here XYZ stands for a
-specific section name mentioned below, such as “Acknowledgements”,
-“Dedications”, “Endorsements”, or “History”.) To “Preserve the Title”
-of such a section when you modify the Document means that it remains a
-section “Entitled XYZ” according to this definition.
-
-
The Document may include Warranty Disclaimers next to the notice which
-states that this License applies to the Document. These Warranty
-Disclaimers are considered to be included by reference in this
-License, but only as regards disclaiming warranties: any other
-implication that these Warranty Disclaimers may have is void and has
-no effect on the meaning of this License.
-
-
VERBATIM COPYING
-
-
You may copy and distribute the Document in any medium, either
-commercially or noncommercially, provided that this License, the
-copyright notices, and the license notice saying this License applies
-to the Document are reproduced in all copies, and that you add no other
-conditions whatsoever to those of this License. You may not use
-technical measures to obstruct or control the reading or further
-copying of the copies you make or distribute. However, you may accept
-compensation in exchange for copies. If you distribute a large enough
-number of copies you must also follow the conditions in section 3.
-
-
You may also lend copies, under the same conditions stated above, and
-you may publicly display copies.
-
-
COPYING IN QUANTITY
-
-
If you publish printed copies (or copies in media that commonly have
-printed covers) of the Document, numbering more than 100, and the
-Document’s license notice requires Cover Texts, you must enclose the
-copies in covers that carry, clearly and legibly, all these Cover
-Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on
-the back cover. Both covers must also clearly and legibly identify
-you as the publisher of these copies. The front cover must present
-the full title with all words of the title equally prominent and
-visible. You may add other material on the covers in addition.
-Copying with changes limited to the covers, as long as they preserve
-the title of the Document and satisfy these conditions, can be treated
-as verbatim copying in other respects.
-
-
If the required texts for either cover are too voluminous to fit
-legibly, you should put the first ones listed (as many as fit
-reasonably) on the actual cover, and continue the rest onto adjacent
-pages.
-
-
If you publish or distribute Opaque copies of the Document numbering
-more than 100, you must either include a machine-readable Transparent
-copy along with each Opaque copy, or state in or with each Opaque copy
-a computer-network location from which the general network-using
-public has access to download using public-standard network protocols
-a complete Transparent copy of the Document, free of added material.
-If you use the latter option, you must take reasonably prudent steps,
-when you begin distribution of Opaque copies in quantity, to ensure
-that this Transparent copy will remain thus accessible at the stated
-location until at least one year after the last time you distribute an
-Opaque copy (directly or through your agents or retailers) of that
-edition to the public.
-
-
It is requested, but not required, that you contact the authors of the
-Document well before redistributing any large number of copies, to give
-them a chance to provide you with an updated version of the Document.
-
-
MODIFICATIONS
-
-
You may copy and distribute a Modified Version of the Document under
-the conditions of sections 2 and 3 above, provided that you release
-the Modified Version under precisely this License, with the Modified
-Version filling the role of the Document, thus licensing distribution
-and modification of the Modified Version to whoever possesses a copy
-of it. In addition, you must do these things in the Modified Version:
-
-
-
Use in the Title Page (and on the covers, if any) a title distinct
-from that of the Document, and from those of previous versions
-(which should, if there were any, be listed in the History section
-of the Document). You may use the same title as a previous version
-if the original publisher of that version gives permission.
-
-
List on the Title Page, as authors, one or more persons or entities
-responsible for authorship of the modifications in the Modified
-Version, together with at least five of the principal authors of the
-Document (all of its principal authors, if it has fewer than five),
-unless they release you from this requirement.
-
-
State on the Title page the name of the publisher of the
-Modified Version, as the publisher.
-
-
Preserve all the copyright notices of the Document.
-
-
Add an appropriate copyright notice for your modifications
-adjacent to the other copyright notices.
-
-
Include, immediately after the copyright notices, a license notice
-giving the public permission to use the Modified Version under the
-terms of this License, in the form shown in the Addendum below.
-
-
Preserve in that license notice the full lists of Invariant Sections
-and required Cover Texts given in the Document’s license notice.
-
-
Include an unaltered copy of this License.
-
-
Preserve the section Entitled “History”, Preserve its Title, and add
-to it an item stating at least the title, year, new authors, and
-publisher of the Modified Version as given on the Title Page. If
-there is no section Entitled “History” in the Document, create one
-stating the title, year, authors, and publisher of the Document as
-given on its Title Page, then add an item describing the Modified
-Version as stated in the previous sentence.
-
-
Preserve the network location, if any, given in the Document for
-public access to a Transparent copy of the Document, and likewise
-the network locations given in the Document for previous versions
-it was based on. These may be placed in the “History” section.
-You may omit a network location for a work that was published at
-least four years before the Document itself, or if the original
-publisher of the version it refers to gives permission.
-
-
For any section Entitled “Acknowledgements” or “Dedications”, Preserve
-the Title of the section, and preserve in the section all the
-substance and tone of each of the contributor acknowledgements and/or
-dedications given therein.
-
-
Preserve all the Invariant Sections of the Document,
-unaltered in their text and in their titles. Section numbers
-or the equivalent are not considered part of the section titles.
-
-
Delete any section Entitled “Endorsements”. Such a section
-may not be included in the Modified Version.
-
-
Do not retitle any existing section to be Entitled “Endorsements” or
-to conflict in title with any Invariant Section.
-
-
Preserve any Warranty Disclaimers.
-
-
-
If the Modified Version includes new front-matter sections or
-appendices that qualify as Secondary Sections and contain no material
-copied from the Document, you may at your option designate some or all
-of these sections as invariant. To do this, add their titles to the
-list of Invariant Sections in the Modified Version’s license notice.
-These titles must be distinct from any other section titles.
-
-
You may add a section Entitled “Endorsements”, provided it contains
-nothing but endorsements of your Modified Version by various
-parties—for example, statements of peer review or that the text has
-been approved by an organization as the authoritative definition of a
-standard.
-
-
You may add a passage of up to five words as a Front-Cover Text, and a
-passage of up to 25 words as a Back-Cover Text, to the end of the list
-of Cover Texts in the Modified Version. Only one passage of
-Front-Cover Text and one of Back-Cover Text may be added by (or
-through arrangements made by) any one entity. If the Document already
-includes a cover text for the same cover, previously added by you or
-by arrangement made by the same entity you are acting on behalf of,
-you may not add another; but you may replace the old one, on explicit
-permission from the previous publisher that added the old one.
-
-
The author(s) and publisher(s) of the Document do not by this License
-give permission to use their names for publicity for or to assert or
-imply endorsement of any Modified Version.
-
-
COMBINING DOCUMENTS
-
-
You may combine the Document with other documents released under this
-License, under the terms defined in section 4 above for modified
-versions, provided that you include in the combination all of the
-Invariant Sections of all of the original documents, unmodified, and
-list them all as Invariant Sections of your combined work in its
-license notice, and that you preserve all their Warranty Disclaimers.
-
-
The combined work need only contain one copy of this License, and
-multiple identical Invariant Sections may be replaced with a single
-copy. If there are multiple Invariant Sections with the same name but
-different contents, make the title of each such section unique by
-adding at the end of it, in parentheses, the name of the original
-author or publisher of that section if known, or else a unique number.
-Make the same adjustment to the section titles in the list of
-Invariant Sections in the license notice of the combined work.
-
-
In the combination, you must combine any sections Entitled “History”
-in the various original documents, forming one section Entitled
-“History”; likewise combine any sections Entitled “Acknowledgements”,
-and any sections Entitled “Dedications”. You must delete all
-sections Entitled “Endorsements.”
-
-
COLLECTIONS OF DOCUMENTS
-
-
You may make a collection consisting of the Document and other documents
-released under this License, and replace the individual copies of this
-License in the various documents with a single copy that is included in
-the collection, provided that you follow the rules of this License for
-verbatim copying of each of the documents in all other respects.
-
-
You may extract a single document from such a collection, and distribute
-it individually under this License, provided you insert a copy of this
-License into the extracted document, and follow this License in all
-other respects regarding verbatim copying of that document.
-
-
AGGREGATION WITH INDEPENDENT WORKS
-
-
A compilation of the Document or its derivatives with other separate
-and independent documents or works, in or on a volume of a storage or
-distribution medium, is called an “aggregate” if the copyright
-resulting from the compilation is not used to limit the legal rights
-of the compilation’s users beyond what the individual works permit.
-When the Document is included in an aggregate, this License does not
-apply to the other works in the aggregate which are not themselves
-derivative works of the Document.
-
-
If the Cover Text requirement of section 3 is applicable to these
-copies of the Document, then if the Document is less than one half of
-the entire aggregate, the Document’s Cover Texts may be placed on
-covers that bracket the Document within the aggregate, or the
-electronic equivalent of covers if the Document is in electronic form.
-Otherwise they must appear on printed covers that bracket the whole
-aggregate.
-
-
TRANSLATION
-
-
Translation is considered a kind of modification, so you may
-distribute translations of the Document under the terms of section 4.
-Replacing Invariant Sections with translations requires special
-permission from their copyright holders, but you may include
-translations of some or all Invariant Sections in addition to the
-original versions of these Invariant Sections. You may include a
-translation of this License, and all the license notices in the
-Document, and any Warranty Disclaimers, provided that you also include
-the original English version of this License and the original versions
-of those notices and disclaimers. In case of a disagreement between
-the translation and the original version of this License or a notice
-or disclaimer, the original version will prevail.
-
-
If a section in the Document is Entitled “Acknowledgements”,
-“Dedications”, or “History”, the requirement (section 4) to Preserve
-its Title (section 1) will typically require changing the actual
-title.
-
-
TERMINATION
-
-
You may not copy, modify, sublicense, or distribute the Document except
-as expressly provided for under this License. Any other attempt to
-copy, modify, sublicense or distribute the Document is void, and will
-automatically terminate your rights under this License. However,
-parties who have received copies, or rights, from you under this
-License will not have their licenses terminated so long as such
-parties remain in full compliance.
-
-
FUTURE REVISIONS OF THIS LICENSE
-
-
The Free Software Foundation may publish new, revised versions
-of the GNU Free Documentation License from time to time. Such new
-versions will be similar in spirit to the present version, but may
-differ in detail to address new problems or concerns. See
-http://www.gnu.org/copyleft/.
-
-
Each version of the License is given a distinguishing version number.
-If the Document specifies that a particular numbered version of this
-License “or any later version” applies to it, you have the option of
-following the terms and conditions either of that specified version or
-of any later version that has been published (not as a draft) by the
-Free Software Foundation. If the Document does not specify a version
-number of this License, you may choose any version ever published (not
-as a draft) by the Free Software Foundation.
-
-
-
-
ADDENDUM: How to use this License for your documents
-
-
To use this License in a document you have written, include a copy of
-the License in the document and put the following copyright and
-license notices just after the title page:
-
-
-
Copyright (C) yearyour name.
- Permission is granted to copy, distribute and/or modify this document
- under the terms of the GNU Free Documentation License, Version 1.2
- or any later version published by the Free Software Foundation;
- with no Invariant Sections, no Front-Cover Texts, and no Back-Cover
- Texts. A copy of the license is included in the section entitled ``GNU
- Free Documentation License''.
-
-
-
If you have Invariant Sections, Front-Cover Texts and Back-Cover Texts,
-replace the “with…Texts.” line with this:
-
-
-
with the Invariant Sections being list their titles, with
- the Front-Cover Texts being list, and with the Back-Cover Texts
- being list.
-
-
-
If you have Invariant Sections without Cover Texts, or some other
-combination of the three, merge those two alternatives to suit the
-situation.
-
-
If your document contains nontrivial examples of program code, we
-recommend releasing these examples in parallel under your choice of
-free software license, such as the GNU General Public License,
-to permit their use in free software.
-
Permission is granted to copy, distribute and/or modify this document
-under the terms of the GNU Free Documentation License, Version 1.2
-or any later version published by the Free Software Foundation;
-with no Invariant Sections, no Front-Cover Texts, and no Back-Cover
-Texts. A copy of the license is included in the section entitled “GNU
-Free Documentation License.”
-
There are 3 steps to prepare the plot in MathGL: (1) prepare data to be plotted, (2) setup plot, (3) plot data. Let me show this on the example of surface plotting.
-
-
First we need the data. MathGL use its own class mglData to handle data arrays (see Data processing). This class give ability to handle data arrays by more or less format independent way. So, create it
-
int main()
- {
- mglData dat(30,40); // data to for plotting
- for(long i=0;i<30;i++) for(long j=0;j<40;j++)
- dat.a[i+30*j] = 1/(1+(i-15)*(i-15)/225.+(j-20)*(j-20)/400.);
-
Here I create matrix 30*40 and initialize it by formula. Note, that I use long type for indexes i, j because data arrays can be really large and long type will automatically provide proper indexing.
-
-
Next step is setup of the plot. The only setup I need is axis rotation and lighting.
-
mglGraph gr; // class for plot drawing
- gr.Rotate(50,60); // rotate axis
- gr.Light(true); // enable lighting
-
-
Everything is ready. And surface can be plotted.
-
gr.Surf(dat); // plot surface
-
Basically plot is done. But I decide to add yellow (‘y’ color, see Color styles) contour lines on the surface. To do it I can just add:
-
gr.Cont(dat,"y"); // plot yellow contour lines
-
This demonstrate one of base MathGL concept (see, General concepts) – “new drawing never clears things drawn already”. So, you can just consequently call different plotting functions to obtain “combined” plot. For example, if one need to draw axis then he can just call one more plotting function
-
gr.Axis(); // draw axis
-
-
Now picture is ready and we can save it in a file.
-
gr.WriteFrame("sample.png"); // save it
- }
-
-
To compile your program, you need to specify the linker option -lmgl.
-
-
This is enough for a compilation of console program or with external (non-MathGL) window library. If you want to use FLTK or Qt windows provided by MathGL then you need to add the option -lmgl-wnd.
-
MathGL library provides several tools for parsing MGL scripts. There is tools saving it to bitmap or vectorial images (mglconv). Tool mglview show MGL script and allow to rotate and setup the image. Another feature of mglview is loading *.mgld files (see ExportMGLD()) for quick viewing 3d pictures.
-
-
Both tools have similar set of arguments. They can be name of script file or options. You can use ‘-’ as script name for using standard input (i.e. pipes). Options are:
-
-
-1str
-set str as argument $1 for script;
-
...
-...
-
-9str
-set str as argument $9 for script;
-
-Lloc
-set locale to loc;
-
-sfname
-set MGL script for setting up the plot;
-
-h
-print help message.
-
-
Additionally mglconv have following options:
-
-
-Aval
-add val into the list of animation parameters;
-
-Cv1:v2[:dv]
-add values from v1 ot v2 with step dv (default is 1) into the list of animation parameters;
-
-oname
-set output file name;
-
-n
-disable default output (script should save results by itself);
-
Also you can create animated GIF file or a set of JPEG files with names ‘frameNNNN.jpg’ (here ‘NNNN’ is frame index). Values of the parameter $0 for making animation can be specified inside the script by comment ##a val for each value val (one comment for one value) or by option(s) ‘-A val’. Also you can specify a cycle for animation by comment ##c v1 v2 dv or by option -C v1:v2:dv. In the case of found/specified animation parameters, tool will execute script several times – once for each value of $0.
-
-
-
MathGL also provide another simple tool mgl.cgi which parse MGL script from CGI request and send back produced PNG file. Usually this program should be placed in /usr/lib/cgi-bin/. But you need to put this program by yourself due to possible security issues and difference of Apache server settings.
-
The rotation, shift, zooming, switching on/off transparency and lighting can be done with help of tool-buttons (for mglWindow) or by hot-keys: ‘a’, ‘d’, ‘w’, ‘s’ for plot rotation, ‘r’ and ‘f’ switching on/off transparency and lighting. Press ‘x’ for exit (or closing the window).
-
-
In this example function sample rotates axes (Rotate(), see Subplots and rotation) and draws the bounding box (Box()). Drawing is placed in separate function since it will be used on demand when window canvas needs to be redrawn.
-
Another way of using MathGL library is the direct writing of the picture to the file. It is most usable for plot creation during long calculation or for using of small programs (like Matlab or Scilab scripts) for visualizing repetitive sets of data. But the speed of drawing is much higher in comparison with a script language.
-
-
The following code produces a bitmap PNG picture:
-
#include <mgl2/mgl.h>
-int main(int ,char **)
-{
- mglGraph gr;
- gr.Alpha(true); gr.Light(true);
- sample(&gr); // The same drawing function.
- gr.WritePNG("test.png"); // Don't forget to save the result!
- return 0;
-}
-
For compilation, you need only libmgl library not the one with widgets
-
gcc test.cpp -lmgl
-
This can be important if you create a console program in computer/cluster where X-server (and widgets) is inaccessible.
-
-
The only difference from the previous variant (using windows) is manual switching on the transparency Alpha and lightning Light, if you need it. The usage of frames (see Animation) is not advisable since the whole image is prepared each time. If function sample contains frames then only last one will be saved to the file. In principle, one does not need to separate drawing functions in case of direct file writing in consequence of the single calling of this function for each picture. However, one may use the same drawing procedure to create a plot with changeable parameters, to export in different file types, to emphasize the drawing code and so on. So, in future I will put the drawing in the separate function.
-
-
The code for export into other formats (for example, into vector EPS file) looks the same:
-
#include <mgl2/mgl.h>
-int main(int ,char **)
-{
- mglGraph gr;
- gr.Light(true);
- sample(&gr); // The same drawing function.
- gr.WriteEPS("test.eps"); // Don't forget to save the result!
- return 0;
-}
-
The difference from the previous one is using other function WriteEPS() for EPS format instead of function WritePNG(). Also, there is no switching on of the plot transparency Alpha since EPS format does not support it.
-
Widget classes (mglWindow, mglGLUT) support a delayed drawing, when all plotting functions are called once at the beginning of writing to memory lists. Further program displays the saved lists faster. Resulting redrawing will be faster but it requires sufficient memory. Several lists (frames) can be displayed one after another (by pressing ‘,’, ‘.’) or run as cinema. To switch these feature on one needs to modify function sample:
-
int sample(mglGraph *gr)
-{
- gr->NewFrame(); // the first frame
- gr->Rotate(60,40);
- gr->Box();
- gr->EndFrame(); // end of the first frame
- gr->NewFrame(); // the second frame
- gr->Box();
- gr->Axis("xy");
- gr->EndFrame(); // end of the second frame
- return gr->GetNumFrame(); // returns the frame number
-}
-
First, the function creates a frame by calling NewFrame() for rotated axes and draws the bounding box. The function EndFrame()must be called after the frame drawing! The second frame contains the bounding box and axes Axis("xy") in the initial (unrotated) coordinates. Function sample returns the number of created frames GetNumFrame().
-
-
Note, that animation can be also done as visualization of running calculations (see Draw and calculate).
-
-
Pictures with animation can be saved in file(s) as well. You can: export in animated GIF, or save each frame in separate file (usually JPEG) and convert these files into the movie (for example, by help of ImageMagic). Let me show both methods.
-
-
The simplest methods is making animated GIF. There are 3 steps: (1) open GIF file by StartGIF() function; (2) create the frames by calling NewFrame() before and EndFrame() after plotting; (3) close GIF by CloseGIF() function. So the simplest code for “running” sinusoid will look like this:
-
The second way is saving each frame in separate file (usually JPEG) and later make the movie from them. MathGL have special function for saving frames – it is WriteFrame(). This function save each frame with automatic name ‘frame0001.jpg, frame0002.jpg’ and so on. Here prefix ‘frame’ is defined by PlotId variable of mglGraph class. So the similar code will look like this:
-
Created files can be converted to movie by help of a lot of programs. For example, you can use ImageMagic (command ‘convert frame*.jpg movie.mpg’), MPEG library, GIMP and so on.
-
-
Finally, you can use mglconv tool for doing the same with MGL scripts (see Utilities).
-
The last way of MathGL using is the drawing in memory. Class mglGraph allows one to create a bitmap picture in memory. Further this picture can be displayed in window by some window libraries (like wxWidgets, FLTK, Windows GDI and so on). For example, the code for drawing in wxWidget library looks like:
-
void MyForm::OnPaint(wxPaintEvent& event)
-{
- int w,h,x,y;
- GetClientSize(&w,&h); // size of the picture
- mglGraph gr(w,h);
-
- gr.Alpha(true); // draws something using MathGL
- gr.Light(true);
- sample(&gr,NULL);
-
- wxImage img(w,h,gr.GetRGB(),true);
- ToolBar->GetSize(&x,&y); // gets a height of the toolbar if any
- wxPaintDC dc(this); // and draws it
- dc.DrawBitmap(wxBitmap(img),0,y);
-}
-
The drawing in other libraries is most the same.
-
MathGL can be used to draw plots in parallel with some external calculations. The simplest way for this is the usage of mglDraw class. At this you should enable pthread for widgets by setting enable-pthr-widget=ON at configure stage (it is set by default).
-First, you need to inherit you class from mglDraw class, define virtual members Draw() and Calc() which will draw the plot and proceed calculations. You may want to add the pointer mglWnd *wnd; to window with plot for interacting with them. Finally, you may add any other data or member functions. The sample class is shown below
-
class myDraw : public mglDraw
-{
- mglPoint pnt; // some variable for changeable data
- long i; // another variable to be shown
- mglWnd *wnd; // external window for plotting
-public:
- myDraw(mglWnd *w=0) : mglDraw() { wnd=w; }
- void SetWnd(mglWnd *w) { wnd=w; }
- int Draw(mglGraph *gr)
- {
- gr->Line(mglPoint(),pnt,"Ar2");
- char str[16]; snprintf(str,15,"i=%ld",i);
- gr->Puts(mglPoint(),str);
- return 0;
- }
- void Calc()
- {
- for(i=0;;i++) // do calculation
- {
- long_calculations();// which can be very long
- Check(); // check if need pause
- pnt.Set(2*mgl_rnd()-1,2*mgl_rnd()-1);
- if(wnd) wnd->Update();
- }
- }
-} dr;
-
There is only one issue here. Sometimes you may want to pause calculations to view result carefully, or save state, or change something. So, you need to provide a mechanism for pausing. Class mglDraw provide function Check(); which check if toolbutton with pause is pressed and wait until it will be released. This function should be called in a "safety" places, where you can pause the calculation (for example, at the end of time step). Also you may add call exit(0); at the end of Calc(); function for closing window and exit after finishing calculations.
-Finally, you need to create a window itself and run calculations.
-
int main(int argc,char **argv)
-{
- mglFLTK gr(&dr,"Multi-threading test"); // create window
- dr.SetWnd(&gr); // pass window pointer to yours class
- dr.Run(); // run calculations
- gr.Run(); // run event loop for window
- return 0;
-}
-
-
Note, that you can reach the similar functionality without using mglDraw class (i.e. even for pure C code).
-
mglFLTK *gr=NULL; // pointer to window
-void *calc(void *) // function with calculations
-{
- mglPoint pnt; // some data for plot
- for(long i=0;;i++) // do calculation
- {
- long_calculations(); // which can be very long
- pnt.Set(2*mgl_rnd()-1,2*mgl_rnd()-1);
- if(gr)
- {
- gr->Clf(); // make new drawing
- // draw something
- gr->Line(mglPoint(),pnt,"Ar2");
- char str[16]; snprintf(str,15,"i=%ld",i);
- gr->Puts(mglPoint(),str);
- // don't forgot to update window
- gr->Update();
- }
- }
-}
-int main(int argc,char **argv)
-{
- static pthread_t thr;
- pthread_create(&thr,0,calc,0); // create separate thread for calculations
- pthread_detach(thr); // and detach it
- gr = new mglFLTK; // now create window
- gr->Run(); // and run event loop
- return 0;
-}
-
This sample is exactly the same as one with mglDraw class, but it don’t have functionality for pausing calculations. If you need it then you have to create global mutex (like pthread_mutex_t *mutex = pthread_mutex_init(&mutex,NULL);), set it to window (like gr->SetMutex(mutex);) and periodically check it at calculations (like pthread_mutex_lock(&mutex); pthread_mutex_unlock(&mutex);).
-
-
Finally, you can put the event-handling loop in separate instead of yours code by using RunThr() function instead of Run() one. Unfortunately, such method work well only for FLTK windows and only if pthread support was enabled. Such limitation come from the Qt requirement to be run in the primary thread only. The sample code will be:
-
int main(int argc,char **argv)
-{
- mglFLTK gr("test");
- gr.RunThr(); // <-- need MathGL version which use pthread for widgets
- mglPoint pnt; // some data
- for(int i=0;i<10;i++) // do calculation
- {
- long_calculations();// which can be very long
- pnt.Set(2*mgl_rnd()-1,2*mgl_rnd()-1);
- gr.Clf(); // make new drawing
- gr.Line(mglPoint(),pnt,"Ar2");
- char str[10] = "i=0"; str[3] = '0'+i;
- gr->Puts(mglPoint(),str);
- gr.Update(); // update window
- }
- return 0; // finish calculations and close the window
-}
-
MathGL have several interface widgets for different widget libraries. There are QMathGL for Qt, Fl_MathGL for FLTK. These classes provide control which display MathGL graphics. Unfortunately there is no uniform interface for widget classes because all libraries have slightly different set of functions, features and so on. However the usage of MathGL widgets is rather simple. Let me show it on the example of QMathGL.
-
-
First of all you have to define the drawing function or inherit a class from mglDraw class. After it just create a window and setup QMathGL instance as any other Qt widget:
-
#include <QApplication>
-#include <QMainWindow>
-#include <QScrollArea>
-#include <mgl2/qmathgl.h>
-int main(int argc,char **argv)
-{
- QApplication a(argc,argv);
- QMainWindow *Wnd = new QMainWindow;
- Wnd->resize(810,610); // for fill up the QMGL, menu and toolbars
- Wnd->setWindowTitle("QMathGL sample");
- // here I allow to scroll QMathGL -- the case
- // then user want to prepare huge picture
- QScrollArea *scroll = new QScrollArea(Wnd);
-
- // Create and setup QMathGL
- QMathGL *QMGL = new QMathGL(Wnd);
-//QMGL->setPopup(popup); // if you want to setup popup menu for QMGL
- QMGL->setDraw(sample);
- // or use QMGL->setDraw(foo); for instance of class Foo:public mglDraw
- QMGL->update();
-
- // continue other setup (menu, toolbar and so on)
- scroll->setWidget(QMGL);
- Wnd->setCentralWidget(scroll);
- Wnd->show();
- return a.exec();
-}
-
MathGL have possibility to draw resulting plot using OpenGL. This produce resulting plot a bit faster, but with some limitations (especially at use of transparency and lighting). Generally, you need to prepare OpenGL window and call MathGL functions to draw it. There is GLUT interface (see Widget classes) to do it by simple way. Below I show example of OpenGL usage basing on Qt libraries (i.e. by using QGLWidget widget).
-
-
First, one need to define widget class derived from QGLWidget and implement a few methods: resizeGL() called after each window resize, paintGL() for displaying the image on the screen, and initializeGL() for initializing OpenGL. The header file looks as following.
-
#ifndef MAINWINDOW_H
-#define MAINWINDOW_H
-
-#include <QGLWidget>
-#include <mgl2/mgl.h>
-
-class MainWindow : public QGLWidget
-{
- Q_OBJECT
-protected:
- mglGraph *gr; // pointer to MathGL core class
- void resizeGL(int nWidth, int nHeight); // Method called after each window resize
- void paintGL(); // Method to display the image on the screen
- void initializeGL(); // Method to initialize OpenGL
-public:
- MainWindow(QWidget *parent = 0);
- ~MainWindow();
-};
-#endif // MAINWINDOW_H
-
-
The class implementation is rather straightforward. One need to recreate the instance of mglGraph at initializing OpenGL, and ask MathGL to use OpenGL output (set argument 1 in mglGraph constructor). Of course, the mglGraph object should be deleted at destruction. The method resizeGL() just pass new sizes to OpenGL and update viewport sizes. All plotting functions are located in the method paintGL(). At this, one need to add 2 calls: gr->Clf() at beginning for clearing previous OpenGL primitives; and swapBuffers() for showing output on the screen. The source file looks as following.
-
#include "qgl_example.h"
-#include <QApplication>
-//#include <QtOpenGL>
-//-----------------------------------------------------------------------------
-MainWindow::MainWindow(QWidget *parent) : QGLWidget(parent) { gr=0; }
-//-----------------------------------------------------------------------------
-MainWindow::~MainWindow() { if(gr) delete gr; }
-//-----------------------------------------------------------------------------
-void MainWindow::initializeGL() // recreate instance of MathGL core
-{
- if(gr) delete gr;
- gr = new mglGraph(1); // use '1' for argument to force OpenGL output in MathGL
-}
-//-----------------------------------------------------------------------------
-void MainWindow::resizeGL(int w, int h) // standard resize replace
-{
- QGLWidget::resizeGL(w, h);
- glViewport (0, 0, w, h);
-}
-//-----------------------------------------------------------------------------
-void MainWindow::paintGL() // main drawing function
-{
- gr->Clf(); // clear previous OpenGL primitives
- gr->SubPlot(1,1,0);
- gr->Rotate(40,60);
- gr->Light(true);
- gr->AddLight(0,mglPoint(0,0,10),mglPoint(0,0,-1));
- gr->Axis();
- gr->Box();
- gr->FPlot("sin(pi*x)","i2");
- gr->FPlot("cos(pi*x)","|");
- gr->FSurf("cos(2*pi*(x^2+y^2))");
- gr->Finish();
- swapBuffers(); // show output on the screen
-}
-//-----------------------------------------------------------------------------
-int main(int argc, char *argv[]) // create application
-{
- mgl_textdomain(argv?argv[0]:NULL,"");
- QApplication a(argc, argv);
- MainWindow w;
- w.show();
- return a.exec();
-}
-//-----------------------------------------------------------------------------
-
Generally SWIG based classes (including the Python one) are the same as C++ classes. However, there are few tips for using MathGL with PyQt. Below I place a very simple python code which demonstrate how MathGL can be used with PyQt. This code is mostly written by Prof. Dr. Heino Falcke. You can just copy it to a file mgl-pyqt-test.py and execute it from python shell by command execfile("mgl-pyqt-test.py")
-
For using MathGL in MPI program you just need to: (1) plot its own part of data for each running node; (2) collect resulting graphical information in a single program (for example, at node with rank=0); (3) save it. The sample code below demonstrate this for very simple sample of surface drawing.
-
Next step is data creation. For simplicity, I create data arrays with the same sizes for all nodes. At this, you have to create mglGraph object too.
-
-
// initialize data similarly for all nodes
- mglData a(128,256);
- mglGraphMPI gr;
-
-
Now, data should be filled by numbers. In real case, it should be some kind of calculations. But I just fill it by formula.
-
-
// do the same plot for its own range
- char buf[64];
- sprintf(buf,"xrange %g %g",2.*rank/numproc-1,2.*(rank+1)/numproc-1);
- gr.Fill(a,"sin(2*pi*x)",buf);
-
-
It is time to plot the data. Don’t forget to set proper axis range(s) by using parametric form or by using options (as in the sample).
-
-
// plot data in each node
- gr.Clf(); // clear image before making the image
- gr.Rotate(40,60);
- gr.Surf(a,"",buf);
-
-
Finally, let send graphical information to node with rank=0.
-
Now, node with rank=0 have whole image. It is time to save the image to a file. Also, you can add a kind of annotations here – I draw axis and bounding box in the sample.
-
-
if(rank==0)
- {
- gr.Box(); gr.Axis(); // some post processing
- gr.WritePNG("test.png"); // save result
- }
-
-
In my case the program is done, and I finalize MPI. In real program, you can repeat the loop of data calculation and data plotting as many times as you need.
-
-
MPI_Finalize();
- return 0;
-}
-
-
You can type ‘mpic++ test.cpp -lmgl-mpi -lmgl && mpirun -np 8 ./a.out’ for compilation and running the sample program on 8 nodes. Note, that you have to set enable-mpi=ON at MathGL configure to use this feature.
-
Now I show several non-obvious features of MathGL: several subplots in a single picture, curvilinear coordinates, text printing and so on. Generally you may miss this section at first reading.
-
Let me demonstrate possibilities of plot positioning and rotation. MathGL has a set of functions: subplot, inplot, title, aspect and rotate and so on (see Subplots and rotation). The order of their calling is strictly determined. First, one changes the position of plot in image area (functions subplot, inplot and multiplot). Secondly, you can add the title of plot by title function. After that one may rotate the plot (function rotate). Finally, one may change aspects of axes (function aspect). The following code illustrates the aforesaid it:
-
Here I used function Puts for printing the text in arbitrary position of picture (see Text printing). Text coordinates and size are connected with axes. However, text coordinates may be everywhere, including the outside the bounding box. I’ll show its features later in Text features.
-
-
-
-
More complicated sample show how to use most of positioning functions:
-
MathGL library can draw not only the bounding box but also the axes, grids, labels and so on. The ranges of axes and their origin (the point of intersection) are determined by functions SetRange(), SetRanges(), SetOrigin() (see Ranges (bounding box)). Ticks on axis are specified by function SetTicks, SetTicksVal, SetTicksTime (see Ticks). But usually
-
-
Function axis draws axes. Its textual string shows in which directions the axis or axes will be drawn (by default "xyz", function draws axes in all directions). Function grid draws grid perpendicularly to specified directions. Example of axes and grid drawing is:
-
Note, that MathGL can draw not only single axis (which is default). But also several axis on the plot (see right plots). The idea is that the change of settings does not influence on the already drawn graphics. So, for 2-axes I setup the first axis and draw everything concerning it. Then I setup the second axis and draw things for the second axis. Generally, the similar idea allows one to draw rather complicated plot of 4 axis with different ranges (see bottom left plot).
-
-
At this inverted axis can be created by 2 methods. First one is used in this sample – just specify minimal axis value to be large than maximal one. This method work well for 2D axis, but can wrongly place labels in 3D case. Second method is more general and work in 3D case too – just use aspect function with negative arguments. For example, following code will produce exactly the same result for 2D case, but 2nd variant will look better in 3D.
-
Another MathGL feature is fine ticks tunning. By default (if it is not changed by SetTicks function), MathGL try to adjust ticks positioning, so that they looks most human readable. At this, MathGL try to extract common factor for too large or too small axis ranges, as well as for too narrow ranges. Last one is non-common notation and can be disabled by SetTuneTicks function.
-
-
Also, one can specify its own ticks with arbitrary labels by help of SetTicksVal function. Or one can set ticks in time format. In last case MathGL will try to select optimal format for labels with automatic switching between years, months/days, hours/minutes/seconds or microseconds. However, you can specify its own time representation using formats described in http://www.manpagez.com/man/3/strftime/. Most common variants are ‘%X’ for national representation of time, ‘%x’ for national representation of date, ‘%Y’ for year with century.
-
The last sample I want to show in this subsection is Log-axis. From MathGL’s point of view, the log-axis is particular case of general curvilinear coordinates. So, we need first define new coordinates (see also Curvilinear coordinates) by help of SetFunc or SetCoor functions. At this one should wary about proper axis range. So the code looks as following:
-
You can see that MathGL automatically switch to log-ticks as we define log-axis formula (in difference from v.1.*). Moreover, it switch to log-ticks for any formula if axis range will be large enough (see right bottom plot). Another interesting feature is that you not necessary define usual log-axis (i.e. when coordinates are positive), but you can define “minus-log” axis when coordinate is negative (see left bottom plot).
-
As I noted in previous subsection, MathGL support curvilinear coordinates. In difference from other plotting programs and libraries, MathGL uses textual formulas for connection of the old (data) and new (output) coordinates. This allows one to plot in arbitrary coordinates. The following code plots the line y=0, z=0 in Cartesian, polar, parabolic and spiral coordinates:
-
MathGL handle colorbar as special kind of axis. So, most of functions for axis and ticks setup will work for colorbar too. Colorbars can be in log-scale, and generally as arbitrary function scale; common factor of colorbar labels can be separated; and so on.
-
-
But of course, there are differences – colorbars usually located out of bounding box. At this, colorbars can be at subplot boundaries (by default), or at bounding box (if symbol ‘I’ is specified). Colorbars can handle sharp colors. And they can be located at arbitrary position too. The sample code, which demonstrate colorbar features is:
-
Box around the plot is rather useful thing because it allows one to: see the plot boundaries, and better estimate points position since box contain another set of ticks. MathGL provide special function for drawing such box – box function. By default, it draw black or white box with ticks (color depend on transparency type, see Types of transparency). However, you can change the color of box, or add drawing of rectangles at rear faces of box. Also you can disable ticks drawing, but I don’t know why anybody will want it. The sample code, which demonstrate box features is:
-
There are another unusual axis types which are supported by MathGL. These are ternary and quaternary axis. Ternary axis is special axis of 3 coordinates a, b, c which satisfy relation a+b+c=1. Correspondingly, quaternary axis is special axis of 4 coordinates a, b, c, d which satisfy relation a+b+c+d=1.
-
-
Generally speaking, only 2 of coordinates (3 for quaternary) are independent. So, MathGL just introduce some special transformation formulas which treat a as ‘x’, b as ‘y’ (and c as ‘z’ for quaternary). As result, all plotting functions (curves, surfaces, contours and so on) work as usual, but in new axis. You should use ternary function for switching to ternary/quaternary coordinates. The sample code is:
-
MathGL prints text by vector font. There are functions for manual specifying of text position (like Puts) and for its automatic selection (like Label, Legend and so on). MathGL prints text always in specified position even if it lies outside the bounding box. The default size of font is specified by functions SetFontSize* (see Font settings). However, the actual size of output string depends on subplot size (depends on functions SubPlot, InPlot). The switching of the font style (italic, bold, wire and so on) can be done for the whole string (by function parameter) or inside the string. By default MathGL parses TeX-like commands for symbols and indexes (see Font styles).
-
-
Text can be printed as usual one (from left to right), along some direction (rotated text), or along a curve. Text can be printed on several lines, divided by new line symbol ‘\n’.
-
-
Example of MathGL font drawing is:
-
int sample(mglGraph *gr)
-{
- gr->SubPlot(2,2,0,"");
- gr->Putsw(mglPoint(0,1),L"Text can be in ASCII and in Unicode");
- gr->Puts(mglPoint(0,0.6),"It can be \\wire{wire}, \\big{big} or #r{colored}");
- gr->Puts(mglPoint(0,0.2),"One can change style in string: "
- "\\b{bold}, \\i{italic, \\b{both}}");
- gr->Puts(mglPoint(0,-0.2),"Easy to \\a{overline} or "
- "\\u{underline}");
- gr->Puts(mglPoint(0,-0.6),"Easy to change indexes ^{up} _{down} @{center}");
- gr->Puts(mglPoint(0,-1),"It parse TeX: \\int \\alpha \\cdot "
- "\\sqrt3{sin(\\pi x)^2 + \\gamma_{i_k}} dx");
-
- gr->SubPlot(2,2,1,"");
- gr->Puts(mglPoint(0,0.5), "\\sqrt{\\frac{\\alpha^{\\gamma^2}+\\overset 1{\\big\\infty}}{\\sqrt3{2+b}}}", "@", -4);
- gr->Puts(mglPoint(0,-0.5),"Text can be printed\non several lines");
-
- gr->SubPlot(2,2,2,"");
- mglData y; mgls_prepare1d(&y);
- gr->Box(); gr->Plot(y.SubData(-1,0));
- gr->Text(y,"This is very very long string drawn along a curve",":k");
- gr->Text(y,"Another string drawn under a curve","T:r");
-
- gr->SubPlot(2,2,3,"");
- gr->Line(mglPoint(-1,-1),mglPoint(1,-1),"rA");
- gr->Puts(mglPoint(0,-1),mglPoint(1,-1),"Horizontal");
- gr->Line(mglPoint(-1,-1),mglPoint(1,1),"rA");
- gr->Puts(mglPoint(0,0),mglPoint(1,1),"At angle","@");
- gr->Line(mglPoint(-1,-1),mglPoint(-1,1),"rA");
- gr->Puts(mglPoint(-1,0),mglPoint(-1,1),"Vertical");
- return 0;
-}
-
-
-
-
You can change font faces by loading font files by function loadfont. Note, that this is long-run procedure. Font faces can be downloaded from MathGL website or from here. The sample code is:
-
Legend is one of standard ways to show plot annotations. Basically you need to connect the plot style (line style, marker and color) with some text. In MathGL, you can do it by 2 methods: manually using addlegend function; or use ‘legend’ option (see Command options), which will use last plot style. In both cases, legend entries will be added into internal accumulator, which later used for legend drawing itself. clearlegend function allow you to remove all saved legend entries.
-
-
There are 2 features. If plot style is empty then text will be printed without indent. If you want to plot the text with indent but without plot sample then you need to use space ‘’ as plot style. Such style ‘’ will draw a plot sample (line with marker(s)) which is invisible line (i.e. nothing) and print the text with indent as usual one.
-
-
Function legend draw legend on the plot. The position of the legend can be selected automatic or manually. You can change the size and style of text labels, as well as setup the plot sample. The sample code demonstrating legend features is:
-
The last common thing which I want to show in this section is how one can cut off points from plot. There are 4 mechanism for that.
-
-
You can set one of coordinate to NAN value. All points with NAN values will be omitted.
-
-
You can enable cutting at edges by SetCut function. As result all points out of bounding box will be omitted.
-
-
You can set cutting box by SetCutBox function. All points inside this box will be omitted.
-
-
You can define cutting formula by SetCutOff function. All points for which the value of formula is nonzero will be omitted. Note, that this is the slowest variant.
-
-
-
Below I place the code which demonstrate last 3 possibilities:
-
Class mglData contains all functions for the data handling in MathGL (see Data processing). There are several matters why I use class mglData but not a single array: it does not depend on type of data (mreal or double), sizes of data arrays are kept with data, memory working is simpler and safer.
-
FILE *fp=fopen("sin.dat","wt"); // create file first
- for(int i=0;i<50;i++) fprintf(fp,"%g\n",sin(M_PI*i/49.));
- fclose(fp);
-
- mglData y("sin.dat"); // load it
-
At this you can use textual or HDF files, as well as import values from bitmap image (PNG is supported right now).
-
-
at this one can read only part of data
-
FILE *fp-fopen("sin.dat","wt"); // create large file first
- for(int i=0;i<70;i++) fprintf(fp,"%g\n",sin(M_PI*i/49.));
- fclose(fp);
-
- mglData y;
- y.Read("sin.dat",50); // load it
-
-
-
Creation of 2d- and 3d-arrays is mostly the same. But one should keep in mind that class mglData uses flat data representation. For example, matrix 30*40 is presented as flat (1d-) array with length 30*40=1200 (nx=30, ny=40). The element with indexes {i,j} is a[i+nx*j]. So for 2d array we have:
-
The only non-obvious thing here is using multidimensional arrays in C/C++, i.e. arrays defined like mreal dat[40][30];. Since, formally these elements dat[i] can address the memory in arbitrary place you should use the proper function to convert such arrays to mglData object. For C++ this is functions like mglData::Set(mreal **dat, int N1, int N2);. For C this is functions like mgl_data_set_mreal2(HMDT d, const mreal **dat, int N1, int N2);. At this, you should keep in mind that nx=N2 and ny=N1 after conversion.
-
Sometimes the data arrays are so large, that one couldn’t’ copy its values to another array (i.e. into mglData). In this case, he can define its own class derived from mglDataA (see mglDataA class) or can use Link function.
-
-
In last case, MathGL just save the link to an external data array, but not copy it. You should provide the existence of this data array for whole time during which MathGL can use it. Another point is that MathGL will automatically create new array if you’ll try to modify data values by any of mglData functions. So, you should use only function with const modifier if you want still using link to the original data array.
-
-
Creating the link is rather simple – just the same as using Set function
-
MathGL has functions for data processing: differentiating, integrating, smoothing and so on (for more detail, see Data processing). Let us consider some examples. The simplest ones are integration and differentiation. The direction in which operation will be performed is specified by textual string, which may contain symbols ‘x’, ‘y’ or ‘z’. For example, the call of Diff("x") will differentiate data along ‘x’ direction; the call of Integral("xy") perform the double integration of data along ‘x’ and ‘y’ directions; the call of Diff2("xyz") will apply 3d Laplace operator to data and so on. Example of this operations on 2d array a=x*y is presented in code:
-
Data smoothing (function smooth) is more interesting and important. This function has single argument which define type of smoothing and its direction. Now 3 methods are supported: ‘3’ – linear averaging by 3 points, ‘5’ – linear averaging by 5 points, and default one – quadratic averaging by 5 points.
-
-
MathGL also have some amazing functions which is not so important for data processing as useful for data plotting. There are functions for finding envelope (useful for plotting rapidly oscillating data), for data sewing (useful to removing jumps on the phase), for data resizing (interpolation). Let me demonstrate it:
-
Also one can create new data arrays on base of the existing one: extract slice, row or column of data (subdata), summarize along a direction(s) (sum), find distribution of data elements (hist) and so on.
-
-
Another interesting feature of MathGL is interpolation and root-finding. There are several functions for linear and cubic spline interpolation (see Interpolation). Also there is a function evaluate which do interpolation of data array for values of each data element of index data. It look as indirect access to the data elements.
-
-
This function have inverse function solve which find array of indexes at which data array is equal to given value (i.e. work as root finding). But solve function have the issue – usually multidimensional data (2d and 3d ones) have an infinite number of indexes which give some value. This is contour lines for 2d data, or isosurface(s) for 3d data. So, solve function will return index only in given direction, assuming that other index(es) are the same as equidistant index(es) of original data. If data have multiple roots then second (and later) branches can be found by consecutive call(s) of solve function. Let me demonstrate this on the following sample.
-
Let me now show how to plot the data. Next section will give much more examples for all plotting functions. Here I just show some basics. MathGL generally has 2 types of plotting functions. Simple variant requires a single data array for plotting, other data (coordinates) are considered uniformly distributed in axis range. Second variant requires data arrays for all coordinates. It allows one to plot rather complex multivalent curves and surfaces (in case of parametric dependencies). Usually each function have one textual argument for plot style and another textual argument for options (see Command options).
-
-
Note, that the call of drawing function adds something to picture but does not clear the previous plots (as it does in Matlab). Another difference from Matlab is that all setup (like transparency, lightning, axis borders and so on) must be specified before plotting functions.
-
-
Let start for plots for 1D data. Term “1D data” means that data depend on single index (parameter) like curve in parametric form {x(i),y(i),z(i)}, i=1...n. The textual argument allow you specify styles of line and marks (see Line styles). If this parameter is NULL or empty then solid line with color from palette is used (see Palette and colors).
-
-
Below I shall show the features of 1D plotting on base of plot function. Let us start from sinus plot:
-
Style of line is not specified in plot function. So MathGL uses the solid line with first color of palette (this is blue). Next subplot shows array y1 with 2 rows:
-
As previously I did not specify the style of lines. As a result, MathGL again uses solid line with next colors in palette (there are green and red). Now let us plot a circle on the same subplot. The circle is parametric curve x=cos(\pi t), y=sin(\pi t). I will set the color of the circle (dark yellow, ‘Y’) and put marks ‘+’ at point position:
-
Note that solid line is used because I did not specify the type of line. The same picture can be achieved by plot and subdata functions. Let us draw ellipse by orange dash line:
-
Surfaces surf and other 2D plots (see 2D plotting) are drown the same simpler as 1D one. The difference is that the string parameter specifies not the line style but the color scheme of the plot (see Color scheme). Here I draw attention on 4 most interesting color schemes. There is gray scheme where color is changed from black to white (string ‘kw’) or from white to black (string ‘wk’). Another scheme is useful for accentuation of negative (by blue color) and positive (by red color) regions on plot (string ‘"BbwrR"’). Last one is the popular “jet” scheme (string ‘"BbcyrR"’).
-
-
Now I shall show the example of a surface drawing. At first let us switch lightning on
-
int sample(mglGraph *gr)
-{
- gr->Light(true); gr->Light(0,mglPoint(0,0,1));
-
and draw the surface, considering coordinates x,y to be uniformly distributed in axis range
-
Color scheme was not specified. So previous color scheme is used. In this case it is default color scheme (“jet”) for the first plot. Next example is a sphere. The sphere is parametrically specified surface:
-
Drawing of other 2D plots is analogous. The only peculiarity is the usage of flag ‘#’. By default this flag switches on the drawing of a grid on plot (grid or mesh for plots in plain or in volume). However, for isosurfaces (including surfaces of rotation axial) this flag switches the face drawing off. Figure becomes wired. The following code gives example of flag ‘#’ using (compare with normal function drawing as in its description):
-
In this section I’ve included some small hints and advices for the improving of the quality of plots and for the demonstration of some non-trivial features of MathGL library. In contrast to previous examples I showed mostly the idea but not the whole drawing function.
-
As I noted above, MathGL functions (except the special one, like Clf()) do not erase the previous plotting but just add the new one. It allows one to draw “compound” plots easily. For example, popular Matlab command surfc can be emulated in MathGL by 2 calls:
-
Surf(a);
- Cont(a, "_"); // draw contours at bottom
-
Here a is 2-dimensional data for the plotting, -1 is the value of z-coordinate at which the contour should be plotted (at the bottom in this example). Analogously, one can draw density plot instead of contour lines and so on.
-
-
Another nice plot is contour lines plotted directly on the surface:
-
Light(true); // switch on light for the surface
- Surf(a, "BbcyrR"); // select 'jet' colormap for the surface
- Cont(a, "y"); // and yellow color for contours
-
The possible difficulties arise in black&white case, when the color of the surface can be close to the color of a contour line. In that case I may suggest the following code:
-
Light(true); // switch on light for the surface
- Surf(a, "kw"); // select 'gray' colormap for the surface
- CAxis(-1,0); // first draw for darker surface colors
- Cont(a, "w"); // white contours
- CAxis(0,1); // now draw for brighter surface colors
- Cont(a, "k"); // black contours
- CAxis(-1,1); // return color range to original state
-
The idea is to divide the color range on 2 parts (dark and bright) and to select the contrasting color for contour lines for each of part.
-
-
Similarly, one can plot flow thread over density plot of vector field amplitude (this is another amusing plot from Matlab) and so on. The list of compound graphics can be prolonged but I hope that the general idea is clear.
-
-
Just for illustration I put here following sample code:
-
MathGL library has advanced features for setting and handling the surface transparency. The simplest way to add transparency is the using of function alpha. As a result, all further surfaces (and isosurfaces, density plots and so on) become transparent. However, their look can be additionally improved.
-
-
The value of transparency can be different from surface to surface. To do it just use SetAlphaDef before the drawing of the surface, or use option alpha (see Command options). If its value is close to 0 then the surface becomes more and more transparent. Contrary, if its value is close to 1 then the surface becomes practically non-transparent.
-
-
Also you can change the way how the light goes through overlapped surfaces. The function SetTranspType defines it. By default the usual transparency is used (‘0’) – surfaces below is less visible than the upper ones. A “glass-like” transparency (‘1’) has a different look – each surface just decreases the background light (the surfaces are commutable in this case).
-
-
A “neon-like” transparency (‘2’) has more interesting look. In this case a surface is the light source (like a lamp on the dark background) and just adds some intensity to the color. At this, the library sets automatically the black color for the background and changes the default line color to white.
-
-
As example I shall show several plots for different types of transparency. The code is the same except the values of SetTranspType function:
-
You can easily make 3D plot and draw its x-,y-,z-projections (like in CAD) by using ternary function with arguments: 4 for Cartesian, 5 for Ternary and 6 for Quaternary coordinates. The sample code is:
-
MathGL can add a fog to the image. Its switching on is rather simple – just use fog function. There is the only feature – fog is applied for whole image. Not to particular subplot. The sample code is:
-
In contrast to the most of other programs, MathGL supports several (up to 10) light sources. Moreover, the color each of them can be different: white (this is usual), yellow, red, cyan, green and so on. The use of several light sources may be interesting for the highlighting of some peculiarities of the plot or just to make an amusing picture. Note, each light source can be switched on/off individually. The sample code is:
-
Additionally, you can use local light sources and set to use diffuse reflection instead of specular one (by default) or both kinds. Note, I use attachlight command to keep light settings relative to subplot.
-
MathGL provide a set of functions for drawing primitives (see Primitives). Primitives are low level object, which used by most of plotting functions. Picture below demonstrate some of commonly used primitives.
-
-
-
-
Generally, you can create arbitrary new kind of plot using primitives. For example, MathGL don’t provide any special functions for drawing molecules. However, you can do it using only one type of primitives drop. The sample code is:
-
Moreover, some of special plots can be more easily produced by primitives rather than by specialized function. For example, Venn diagram can be produced by Error plot:
-
Short-time Fourier Analysis (stfa) is one of informative method for analyzing long rapidly oscillating 1D data arrays. It is used to determine the sinusoidal frequency and phase content of local sections of a signal as it changes over time.
-
-
MathGL can find and draw STFA result. Just to show this feature I give following sample. Initial data arrays is 1D arrays with step-like frequency. Exactly this you can see at bottom on the STFA plot. The sample code is:
-
Sometime ago I worked with mapping and have a question about its visualization. Let me remember you that mapping is some transformation rule for one set of number to another one. The 1d mapping is just an ordinary function – it takes a number and transforms it to another one. The 2d mapping (which I used) is a pair of functions which take 2 numbers and transform them to another 2 ones. Except general plots (like surfc, surfa) there is a special plot – Arnold diagram. It shows the area which is the result of mapping of some initial area (usually square).
-
-
I tried to make such plot in map. It shows the set of points or set of faces, which final position is the result of mapping. At this, the color gives information about their initial position and the height describes Jacobian value of the transformation. Unfortunately, it looks good only for the simplest mapping but for the real multivalent quasi-chaotic mapping it produces a confusion. So, use it if you like :).
-
functions subdata and evaluate for indirect access to data elements;
-
functions refill, gspline and datagrid which fill regular (rectangular) data array by interpolated values.
-
-
-
The usage of first category is rather straightforward and don’t need any special comments.
-
-
There is difference in indirect access functions. Function subdata use use step-like interpolation to handle correctly single nan values in the data array. Contrary, function evaluate use local spline interpolation, which give smoother output but spread nan values. So, subdata should be used for specific data elements (for example, for given column), and evaluate should be used for distributed elements (i.e. consider data array as some field). Following sample illustrates this difference:
-
int sample(mglGraph *gr)
-{
- gr->SubPlot(1,1,0,""); gr->Title("SubData vs Evaluate");
- mglData in(9), arg(99), e, s;
- gr->Fill(in,"x^3/1.1"); gr->Fill(arg,"4*x+4");
- gr->Plot(in,"ko "); gr->Box();
- e = in.Evaluate(arg,false); gr->Plot(e,"b.","legend 'Evaluate'");
- s = in.SubData(arg); gr->Plot(s,"r.","legend 'SubData'");
- gr->Legend(2);
-}
-
-
-
-
Example of datagrid usage is done in Making regular data. Here I want to show the peculiarities of refill and gspline functions. Both functions require argument(s) which provide coordinates of the data values, and return rectangular data array which equidistantly distributed in axis range. So, in opposite to evaluate function, refill and gspline can interpolate non-equidistantly distributed data. At this both functions refill and gspline provide continuity of 2nd derivatives along coordinate(s). However, refill is slower but give better (from human point of view) result than global spline gspline due to more advanced algorithm. Following sample illustrates this difference:
-
Sometimes, one have only unregular data, like as data on triangular grids, or experimental results and so on. Such kind of data cannot be used as simple as regular data (like matrices). Only few functions, like dots, can handle unregular data as is.
-
-
However, one can use built in triangulation functions for interpolating unregular data points to a regular data grids. There are 2 ways. First way, one can use triangulation function to obtain list of vertexes for triangles. Later this list can be used in functions like triplot or tricont. Second way consist in usage of datagrid function, which fill regular data grid by interpolated values, assuming that coordinates of the data grid is equidistantly distributed in axis range. Note, you can use options (see Command options) to change default axis range as well as in other plotting functions.
-
int sample(mglGraph *gr)
-{
- mglData x(100), y(100), z(100);
- gr->Fill(x,"2*rnd-1"); gr->Fill(y,"2*rnd-1"); gr->Fill(z,"v^2-w^2",x,y);
- // first way - plot triangular surface for points
- mglData d = mglTriangulation(x,y);
- gr->Title("Triangulation");
- gr->Rotate(40,60); gr->Box(); gr->Light(true);
- gr->TriPlot(d,x,y,z); gr->TriPlot(d,x,y,z,"#k");
- // second way - make regular data and plot it
- mglData g(30,30);
- gr->DataGrid(g,x,y,z); gr->Mesh(g,"m");
-}
-
Using the hist function(s) for making regular distributions is one of useful fast methods to process and plot irregular data. Hist can be used to find some momentum of set of points by specifying weight function. It is possible to create not only 1D distributions but also 2D and 3D ones. Below I place the simplest sample code which demonstrate hist usage:
-
Nonlinear fitting is rather simple. All that you need is the data to fit, the approximation formula and the list of coefficients to fit (better with its initial guess values). Let me demonstrate it on the following simple example. First, let us use sin function with some random noise:
-
mglData dat(100), in(100); //data to be fitted and ideal data
- gr->Fill(dat,"0.4*rnd+0.1+sin(2*pi*x)");
- gr->Fill(in,"0.3+sin(2*pi*x)");
-
The next step is the fitting itself. For that let me specify an initial values ini for coefficients ‘abc’ and do the fitting for approximation formula ‘a+b*sin(c*x)’
-
NOTE! the fitting results may have strong dependence on initial values for coefficients due to algorithm features. The problem is that in general case there are several local "optimums" for coefficients and the program returns only first found one! There are no guaranties that it will be the best. Try for example to set ini[3] = {0, 0, 0} in the code above.
-
Solving of Partial Differential Equations (PDE, including beam tracing) and ray tracing (or finding particle trajectory) are more or less common task. So, MathGL have several functions for that. There are ray for ray tracing, pde for PDE solving, qo2d for beam tracing in 2D case (see Global functions). Note, that these functions take “Hamiltonian” or equations as string values. And I don’t plan now to allow one to use user-defined functions. There are 2 reasons: the complexity of corresponding interface; and the basic nature of used methods which are good for samples but may not good for serious scientific calculations.
-
-
The ray tracing can be done by ray function. Really ray tracing equation is Hamiltonian equation for 3D space. So, the function can be also used for finding a particle trajectory (i.e. solve Hamiltonian ODE) for 1D, 2D or 3D cases. The function have a set of arguments. First of all, it is Hamiltonian which defined the media (or the equation) you are planning to use. The Hamiltonian is defined by string which may depend on coordinates ‘x’, ‘y’, ‘z’, time ‘t’ (for particle dynamics) and momentums ‘p’=p_x, ‘q’=p_y, ‘v’=p_z. Next, you have to define the initial conditions for coordinates and momentums at ‘t’=0 and set the integrations step (default is 0.1) and its duration (default is 10). The Runge-Kutta method of 4-th order is used for integration.
-
This example calculate the reflection from linear layer (media with Hamiltonian ‘p^2+q^2-x-1’=p_x^2+p_y^2-x-1). This is parabolic curve. The resulting array have 7 columns which contain data for {x,y,z,p,q,v,t}.
-
-
The solution of PDE is a bit more complicated. As previous you have to specify the equation as pseudo-differential operator \hat H(x, \nabla) which is called sometime as “Hamiltonian” (for example, in beam tracing). As previously, it is defined by string which may depend on coordinates ‘x’, ‘y’, ‘z’ (but not time!), momentums ‘p’=(d/dx)/i k_0, ‘q’=(d/dy)/i k_0 and field amplitude ‘u’=|u|. The evolutionary coordinate is ‘z’ in all cases. So that, the equation look like du/dz = ik_0 H(x,y,\hat p, \hat q, |u|)[u]. Dependence on field amplitude ‘u’=|u| allows one to solve nonlinear problems too. For example, for nonlinear Shrodinger equation you may set ham="p^2 + q^2 - u^2". Also you may specify imaginary part for wave absorption, like ham = "p^2 + i*x*(x>0)" or ham = "p^2 + i1*x*(x>0)".
-
-
Next step is specifying the initial conditions at ‘z’ equal to minimal z-axis value. The function need 2 arrays for real and for imaginary part. Note, that coordinates x,y,z are supposed to be in specified axis range. So, the data arrays should have corresponding scales. Finally, you may set the integration step and parameter k0=k_0. Also keep in mind, that internally the 2 times large box is used (for suppressing numerical reflection from boundaries) and the equation should well defined even in this extended range.
-
-
Final comment is concerning the possible form of pseudo-differential operator H. At this moment, simplified form of operator H is supported – all “mixed” terms (like ‘x*p’->x*d/dx) are excluded. For example, in 2D case this operator is effectively H = f(p,z) + g(x,z,u). However commutable combinations (like ‘x*q’->x*d/dy) are allowed for 3D case.
-
-
So, for example let solve the equation for beam deflected from linear layer and absorbed later. The operator will have the form ‘"p^2+q^2-x-1+i*0.5*(z+x)*(z>-x)"’ that correspond to equation 1/ik_0 * du/dz + d^2 u/dx^2 + d^2 u/dy^2 + x * u + i (x+z)/2 * u = 0. This is typical equation for Electron Cyclotron (EC) absorption in magnetized plasmas. For initial conditions let me select the beam with plane phase front exp(-48*(x+0.7)^2). The corresponding code looks like this:
-
int sample(mglGraph *gr)
-{
- mglData a,re(128),im(128);
- gr->Fill(re,"exp(-48*(x+0.7)^2)");
- a = gr->PDE("p^2+q^2-x-1+i*0.5*(z+x)*(z>-x)", re, im, 0.01, 30);
- a.Transpose("yxz");
- gr->SubPlot(1,1,0,"<_"); gr->Title("PDE solver");
- gr->SetRange('c',0,1); gr->Dens(a,"wyrRk");
- gr->Axis(); gr->Label('x', "\\i x"); gr->Label('y', "\\i z");
- gr->FPlot("-x", "k|");
- gr->Puts(mglPoint(0, 0.85), "absorption: (x+z)/2 for x+z>0");
- gr->Puts(mglPoint(0,1.1),"Equation: ik_0\\partial_zu + \\Delta u + x\\cdot u + i \\frac{x+z}{2}\\cdot u = 0");
- return 0;
-}
-
-
-
-
The next example is example of beam tracing. Beam tracing equation is special kind of PDE equation written in coordinates accompanied to a ray. Generally this is the same parameters and limitation as for PDE solving but the coordinates are defined by the ray and by parameter of grid width w in direction transverse the ray. So, you don’t need to specify the range of coordinates. BUT there is limitation. The accompanied coordinates are well defined only for smooth enough rays, i.e. then the ray curvature K (which is defined as 1/K^2 = (|r''|^2 |r'|^2 - (r'', r'')^2)/|r'|^6) is much large then the grid width: K>>w. So, you may receive incorrect results if this condition will be broken.
-
-
You may use following code for obtaining the same solution as in previous example:
-
int sample(mglGraph *gr)
-{
- mglData r, xx, yy, a, im(128), re(128);
- const char *ham = "p^2+q^2-x-1+i*0.5*(y+x)*(y>-x)";
- r = mglRay(ham, mglPoint(-0.7, -1), mglPoint(0, 0.5), 0.02, 2);
- gr->SubPlot(1,1,0,"<_"); gr->Title("Beam and ray tracing");
- gr->Plot(r.SubData(0), r.SubData(1), "k");
- gr->Axis(); gr->Label('x', "\\i x"); gr->Label('y', "\\i z");
-
- // now start beam tracing
- gr->Fill(re,"exp(-48*x^2)");
- a = mglQO2d(ham, re, im, r, xx, yy, 1, 30);
- gr->SetRange('c',0, 1);
- gr->Dens(xx, yy, a, "wyrRk");
- gr->FPlot("-x", "k|");
- gr->Puts(mglPoint(0, 0.85), "absorption: (x+y)/2 for x+y>0");
- gr->Puts(mglPoint(0.7, -0.05), "central ray");
- return 0;
-}
-
-
-
-
Note, the pde is fast enough and suitable for many cases routine. However, there is situations then media have both together: strong spatial dispersion and spatial inhomogeneity. In this, case the pde will produce incorrect result and you need to use advanced PDE solver apde. For example, a wave beam, propagated in plasma, described by Hamiltonian exp(-x^2-p^2), will have different solution for using of simplification and advanced PDE solver:
-
Here I want say a few words of plotting phase plains. Phase plain is name for system of coordinates x, x', i.e. a variable and its time derivative. Plot in phase plain is very useful for qualitative analysis of an ODE, because such plot is rude (it topologically the same for a range of ODE parameters). Most often the phase plain {x, x'} is used (due to its simplicity), that allows to analyze up to the 2nd order ODE (i.e. x''+f(x,x')=0).
-
-
The simplest way to draw phase plain in MathGL is using flow function(s), which automatically select several points and draw flow threads. If the ODE have an integral of motion (like Hamiltonian H(x,x')=const for dissipation-free case) then you can use cont function for plotting isolines (contours). In fact. isolines are the same as flow threads, but without arrows on it. Finally, you can directly solve ODE using ode function and plot its numerical solution.
-
-
Let demonstrate this for ODE equation x''-x+3*x^2=0. This is nonlinear oscillator with square nonlinearity. It has integral H=y^2+2*x^3-x^2=Const. Also it have 2 typical stationary points: saddle at {x=0, y=0} and center at {x=1/3, y=0}. Motion at vicinity of center is just simple oscillations, and is stable to small variation of parameters. In opposite, motion around saddle point is non-stable to small variation of parameters, and is very slow. So, calculation around saddle points are more difficult, but more important. Saddle points are responsible for solitons, stochasticity and so on.
-
-
So, let draw this phase plain by 3 different methods. First, draw isolines for H=y^2+2*x^3-x^2=Const – this is simplest for ODE without dissipation. Next, draw flow threads – this is straightforward way, but the automatic choice of starting points is not always optimal. Finally, use ode to check the above plots. At this we need to run ode in both direction of time (in future and in the past) to draw whole plain. Alternatively, one can put starting points far from (or at the bounding box as done in flow) the plot, but this is a more complicated. The sample code is:
-
There is common task in optics to determine properties of wave pulses or wave beams. MathGL provide special function pulse which return the pulse properties (maximal value, center of mass, width and so on). Its usage is rather simple. Here I just illustrate it on the example of Gaussian pulse, where all parameters are obvious.
-
void sample(mglGraph *gr)
-{
- gr->SubPlot(1,1,0,"<_"); gr->Title("Pulse sample");
- // first prepare pulse itself
- mglData a(100); gr->Fill(a,"exp(-6*x^2)");
- // get pulse parameters
- mglData b(a.Pulse('x'));
- // positions and widths are normalized on the number of points. So, set proper axis scale.
- gr->SetRanges(0, a.nx-1, 0, 1);
- gr->Axis(); gr->Plot(a); // draw pulse and axis
- // now visualize found pulse properties
- double m = b[0]; // maximal amplitude
- // approximate position of maximum
- gr->Line(mglPoint(b[1],0), mglPoint(b[1],m),"r=");
- // width at half-maximum (so called FWHM)
- gr->Line(mglPoint(b[1]-b[3]/2,0), mglPoint(b[1]-b[3]/2,m),"m|");
- gr->Line(mglPoint(b[1]+b[3]/2,0), mglPoint(b[1]+b[3]/2,m),"m|");
- gr->Line(mglPoint(0,m/2), mglPoint(a.nx-1,m/2),"h");
- // parabolic approximation near maximum
- char func[128]; sprintf(func,"%g*(1-((x-%g)/%g)^2)",b[0],b[1],b[2]);
- gr->FPlot(func,"g");
-}
-
Sometimes you may prefer to use MGL scripts in yours code. It is simpler (especially in comparison with C/Fortran interfaces) and provide faster way to plot the data with annotations, labels and so on. Class mglParse (see mglParse class parse MGL scripts in C++. It have also the corresponding interface for C/Fortran.
-
-
The key function here is mglParse::Parse() (or mgl_parse() for C/Fortran) which execute one command per string. At this the detailed information about the possible errors or warnings is passed as function value. Or you may execute the whole script as long string with lines separated by ‘\n’. Functions mglParse::Execute() and mgl_parse_text() perform it. Also you may set the values of parameters ‘$0’...‘$9’ for the script by functions mglParse::AddParam() or mgl_add_param(), allow/disable picture resizing, check “once” status and so on. The usage is rather straight-forward.
-
-
The only non-obvious thing is data transition between script and yours program. There are 2 stages: add or find variable; and set data to variable. In C++ you may use functions mglParse::AddVar() and mglParse::FindVar() which return pointer to mglData. In C/Fortran the corresponding functions are mgl_add_var(), mgl_find_var(). This data pointer is valid until next Parse() or Execute() call. Note, you must not delete or free the data obtained from these functions!
-
-
So, some simple example at the end. Here I define a data array, create variable, put data into it and plot it. The C++ code looks like this:
-
int sample(mglGraph *gr)
-{
- gr->Title("MGL parser sample");
- mreal a[100]; // let a_i = sin(4*pi*x), x=0...1
- for(int i=0;i<100;i++)a[i]=sin(4*M_PI*i/99);
- mglParse *parser = new mglParse;
- mglData *d = parser->AddVar("dat");
- d->Set(a,100); // set data to variable
- parser->Execute(gr, "plot dat; xrange 0 1\nbox\naxis");
- // you may break script at any line do something
- // and continue after that
- parser->Execute(gr, "xlabel 'x'\nylabel 'y'\nbox");
- // also you may use cycles or conditions in script
- parser->Execute(gr, "for $0 -1 1 0.1\nline 0 0 -1 $0 'r'\nnext");
- delete parser;
- return 0;
-}
-
The code in C/Fortran looks practically the same:
-
int sample(HMGL gr)
-{
- mgl_title(gr, "MGL parser sample", "", -2);
- double a[100]; // let a_i = sin(4*pi*x), x=0...1
- int i;
- for(i=0;i<100;i++) a[i]=sin(4*M_PI*i/99);
- HMPR parser = mgl_create_parser();
- HMDT d = mgl_parser_add_var(parser, "dat");
- mgl_data_set_double(d,a,100,1,1); // set data to variable
- mgl_parse_text(gr, parser, "plot dat; xrange 0 1\nbox\naxis");
- // you may break script at any line do something
- // and continue after that
- mgl_parse_text(gr, parser, "xlabel 'x'\nylabel 'y'");
- // also you may use cycles or conditions in script
- mgl_parse_text(gr, parser, "for $0 -1 1 0.1\nif $0<0\n"
- "line 0 0 -1 $0 'r':else:line 0 0 -1 $0 'g'\n"
- "endif\nnext");
- mgl_write_png(gr, "test.png", ""); // don't forgot to save picture
- return 0;
-}
-
Command options allow the easy setup of the selected plot by changing global settings only for this plot. Often, options are used for specifying the range of automatic variables (coordinates). However, options allows easily change plot transparency, numbers of line or faces to be drawn, or add legend entries. The sample function for options usage is:
-
As I have noted before, the change of settings will influence only for the further plotting commands. This allows one to create “template” function which will contain settings and primitive drawing for often used plots. Correspondingly one may call this template-function for drawing simplification.
-
-
For example, let one has a set of points (experimental or numerical) and wants to compare it with theoretical law (for example, with exponent law \exp(-x/2), x \in [0, 20]). The template-function for this task is:
-
At this, one will only write a few lines for data drawing:
-
template(gr); // apply settings and default drawing from template
- mglData dat("fname.dat"); // load the data
- // and draw it (suppose that data file have 2 columns)
- gr->Plot(dat.SubData(0),dat.SubData(1),"bx ");
-
A template-function can also contain settings for font, transparency, lightning, color scheme and so on.
-
-
I understand that this is obvious thing for any professional programmer, but I several times receive suggestion about “templates” ... So, I decide to point out it here.
-
One can easily create stereo image in MathGL. Stereo image can be produced by making two subplots with slightly different rotation angles. The corresponding code looks like this:
-
By default MathGL save all primitives in memory, rearrange it and only later draw them on bitmaps. Usually, this speed up drawing, but may require a lot of memory for plots which contain a lot of faces (like cloud, dew). You can use quality function for setting to use direct drawing on bitmap and bypassing keeping any primitives in memory. This function also allow you to decrease the quality of the resulting image but increase the speed of the drawing.
-
-
The code for lowest memory usage looks like this:
-
int sample(mglGraph *gr)
-{
- gr->SetQuality(6); // firstly, set to draw directly on bitmap
- for(i=0;i<1000;i++)
- gr->Sphere(mglPoint(mgl_rnd()*2-1,mgl_rnd()*2-1),0.05);
- return 0;
-}
-
MathGL have possibilities to write textual information into file with variable values. In MGL script you can use save command for that. However, the usual printf(); is simple in C/C++ code. For example, lets create some textual file
-
FILE *fp=fopen("test.txt","w");
-fprintf(fp,"This is test: 0 -> 1 q\n");
-fprintf(fp,"This is test: 1 -> -1 q\n");
-fprintf(fp,"This is test: 2 -> 0 q\n");
-fclose(fp);
-
It contents look like
-
This is test: 0 -> 1 q
-This is test: 1 -> -1 q
-This is test: 2 -> 0 q
-
-
Let assume now that you want to read this values (i.e. [[0,1],[1,-1],[2,0]]) from the file. You can use scanfile for that. The desired values was written using template "This is test: %g -> %g q\n". So, just use
-
mglData a;
-a.ScanFile("test.txt","This is test: %g -> %g");
-
Note, I keep only the leading part of template (i.e. "This is test: %g -> %g" instead of "This is test: %g -> %g q\n"), because there is no important for us information after the second number in the line.
-
Sometimes output plots contain surfaces with a lot of points, and some vector primitives (like axis, text, curves, etc.). Using vector output formats (like EPS or SVG) will produce huge files with possible loss of smoothed lighting. Contrary, the bitmap output may cause the roughness of text and curves. Hopefully, MathGL have a possibility to combine bitmap output for surfaces and vector one for other primitives in the same EPS file, by using rasterize command.
-
-
The idea is to prepare part of picture with surfaces or other "heavy" plots and produce the background image from them by help of rasterize command. Next, we draw everything to be saved in vector form (text, curves, axis and etc.). Note, that you need to clear primitives (use clf command) after rasterize if you want to disable duplication of surfaces in output files (like EPS). Note, that some of output formats (like 3D ones, and TeX) don’t support the background bitmap, and use clf for them will cause the loss of part of picture.
-
-
The sample code is:
-
// first draw everything to be in bitmap output
-gr->FSurf("x^2+y^2", "#", "value 10");
-
-gr->Rasterize(); // set above plots as bitmap background
-gr->Clf(); // clear primitives, to exclude them from file
-
-// now draw everything to be in vector output
-gr->Axis(); gr->Box();
-
-// and save file
-gr->WriteFrame("fname.eps");
-
Yes. Sometimes you may have huge surface and a small set of curves and/or text on the plot. You can use function rasterize just after making surface plot. This will put all plot to bitmap background. At this later plotting will be in vector format. For example, you can do something like following:
-
gr->Surf(x, y, z);
-gr->Rasterize(); // make surface as bitmap
-gr->Axis();
-gr->WriteFrame("fname.eps");
-
Draw bitmap (logo) along whole axis range, which can be changed by Command options. Bitmap can be loaded from file or specified as RGBA values for pixels. Parameter smooth set to draw bitmap without or with color interpolation.
-
-
-
-
-
-
Ðоманда MGL: symbolx y 'id' ['fnt'='' size=-1]
-
Ðоманда MGL: symbolx y z 'id' ['fnt'='' size=-1]
C function: voidmgl_flow3(HMGL gr, HCDT ax, HCDT ay, HCDT az, const char *sch, double sVal, const char *opt)
-
C function: voidmgl_flow3_xyz(HMGL gr, HCDT x, HCDT y, HCDT z, HCDT ax, HCDT ay, HCDT az, const char *sch, double sVal, const char *opt)
-
The function draws flow threads for the 3D vector field {ax, ay, az} parametrically depending on coordinates x, y, z. Flow threads starts from given plane. Option value set the approximate number of threads (default is 5). String sch may contain:
-
-
color scheme – up-half (warm) corresponds to normal flow (like attractor), bottom-half (cold) corresponds to inverse flow (like source);
-
‘x’, ‘z’ for normal of starting plane (default is y-direction);
-
‘v’ for drawing arrows on the threads;
-
‘t’ for drawing tapes of normals in x-y and y-z planes.
-
-
See also flow, pipe, vect. См. Ñаздел flow3 sample, Ð´Ð»Ñ Ð¿ÑимеÑов кода и гÑаÑика.
-
This class provide base functionality for callback drawing and running calculation in separate thread. It is defined in #include <mgl2/wnd.h>. You should make inherited class and implement virtual functions if you need it.
-
-
-
Virtual method on mglDraw: intDraw(mglGraph *gr)
-
This is callback drawing function, which will be called when any redrawing is required for the window. There is support of a list of plots (frames). So as one can prepare a set of frames at first and redraw it fast later (but it requires more memory). Function should return positive number of frames for the list or zero if it will plot directly.
-
-
-
-
Virtual method on mglDraw: voidReload()
-
This is callback function, which will be called if user press menu or toolbutton to reload data.
-
-
-
-
Virtual method on mglDraw: voidClick()
-
This is callback function, which will be called if user click mouse.
-
-
-
-
Virtual method on mglDraw: voidCalc()
-
This is callback function, which will be called if user start calculations in separate thread by calling mglDraw::Run() function. It should periodically call mglDraw::Check() function to check if calculations should be paused.
-
-
-
-
Method on mglDraw: voidRun()
-
Runs mglDraw::Calc() function in separate thread. It also initialize mglDraw::thr variable and unlock mglDraw::mutex. Function is present only if FLTK support for widgets was enabled.
-
-
-
-
Method on mglDraw: voidCancel()
-
Cancels thread with calculations. Function is present only if FLTK support for widgets was enabled.
-
-
-
-
Method on mglDraw: voidPause()
-
Pauses thread with calculations by locking mglDraw::mutex. You should call mglDraw::Continue() to continue calculations. Function is present only if FLTK support for widgets was enabled.
-
-
-
-
Method on mglDraw: voidContinue()
-
Continues calculations by unlocking mglDraw::mutex. Function is present only if FLTK support for widgets was enabled.
-
-
-
-
Method on mglDraw: voidContinue()
-
Checks if calculations should be paused and pause it. Function is present only if FLTK support for widgets was enabled.
-
ÐеÑод клаÑÑа mglData: voidSetList(long n, ...)
-
Allocate memory and set data from variable argument list of double values. Note, you need to specify decimal point ‘.’ for integer values! For example, the code SetList(2,0.,1.); is correct, but the code SetList(2,0,1); is incorrect.
-
These functions change the data in some direction like differentiations, integrations and so on. The direction in which the change will applied is specified by the string parameter, which may contain ‘x’, ‘y’ or ‘z’ characters for 1-st, 2-nd and 3-d dimension correspondingly.
-
There are number of special comments for MGL script, which set some global behavior (like, animation, dialog for parameters and so on). All these special comments starts with double sign ##. Let consider them.
-
-
-
‘##cv1 v2 [dv=1]’
-
Sets the parameter for animation loop relative to variable $0. Here v1 and v2 are initial and final values, dv is the increment.
-
-
-
‘##a val’
-
Adds the parameter val to the list of animation relative to variable $0. You can use it several times (one parameter per line) or combine it with animation loop ##c.
-
-
-
‘##d $I kind|label|par1|par2|...’
-
Creates custom dialog for changing plot properties. Each line adds one widget to the dialog. Here $I is id ($0,$1...$9,$a,$b...$z), label is the label of widget, kind is the kind of the widget:
-
-
’e’ for editor or input line (parameter is initial value) ,
-
’v’ for spinner or counter (parameters are "ini|min|max|step|big_step"),
-
’s’ for slider (parameters are "ini|min|max|step"),
-
’b’ for check box (parameter is "ini"; also understand "on"=1),
-
’c’ for choice (parameters are possible choices).
-
-
Now, it work in FLTK-based mgllab and mglview only.
-
-
You can make custom dialog in C/C++ code too by using one of following functions.
-
Makes custom dialog for parameters ids of element properties defined by args.
-
-
-
At this you need to provide callback function for setting up properties. You can do it by overloading Param() function of mglDraw class or set it manually.
-
-
-
Method on mglDraw: voidParam(char id, const char * val)
There is LaTeX package mgltex (was made by Diego Sejas Viscarra) which allow one to make figures directly from MGL script located in LaTeX file.
-
-
For using this package you need to specify --shell-escape option for latex/pdflatex or manually run mglconv tool with produced MGL scripts for generation of images. Don’t forgot to run latex/pdflatex second time to insert generated images into the output document. Also you need to run pdflatex third time to update converted from EPS images if you are using vector EPS output (default).
-
-
The package may have following options: draft, final — the same as in the graphicx package; on, off — to activate/deactivate the creation of scripts and graphics; comments, nocomments — to make visible/invisible comments contained inside mglcomment environments; jpg, jpeg, png — to export graphics as JPEG/PNG images; eps, epsz — to export to uncompressed/compressed EPS format as primitives; bps, bpsz — to export to uncompressed/compressed EPS format as bitmap (doesn’t work with pdflatex); pdf — to export to 3D PDF; tex — to export to LaTeX/tikz document.
-
-
The package defines the following environments:
-
-
‘mgl’
-
It writes its contents to a general script which has the same name as the LaTeX document, but its extension is .mgl. The code in this environment is compiled and the image produced is included. It takes exactly the same optional arguments as the \includegraphics command, plus an additional argument imgext, which specifies the extension to save the image.
-
-
An example of usage of ‘mgl’ environment would be:
-
\begin{mglfunc}{prepare2d}
- new a 50 40 '0.6*sin(pi*(x+1))*sin(1.5*pi*(y+1))+0.4*cos(0.75*pi*(x+1)*(y+1))'
- new b 50 40 '0.6*cos(pi*(x+1))*cos(1.5*pi*(y+1))+0.4*cos(0.75*pi*(x+1)*(y+1))'
-\end{mglfunc}
-
-\begin{figure}[!ht]
- \centering
- \begin{mgl}[width=0.85\textwidth,height=7.5cm]
- fog 0.5
- call 'prepare2d'
- subplot 2 2 0 : title 'Surf plot (default)' : rotate 50 60 : light on : box : surf a
-
- subplot 2 2 1 : title '"\#" style; meshnum 10' : rotate 50 60 : box
- surf a '#'; meshnum 10
-
- subplot 2 2 2 : title 'Mesh plot' : rotate 50 60 : box
- mesh a
-
- new x 50 40 '0.8*sin(pi*x)*sin(pi*(y+1)/2)'
- new y 50 40 '0.8*cos(pi*x)*sin(pi*(y+1)/2)'
- new z 50 40 '0.8*cos(pi*(y+1)/2)'
- subplot 2 2 3 : title 'parametric form' : rotate 50 60 : box
- surf x y z 'BbwrR'
- \end{mgl}
-\end{figure}
-
-
-
‘mgladdon’
-
It adds its contents to the general script, without producing any image.
-
-
‘mglcode’
-
Is exactly the same as ‘mgl’, but it writes its contents verbatim to its own file, whose name is specified as a mandatory argument.
-
-
‘mglscript’
-
Is exactly the same as ‘mglcode’, but it doesn’t produce any image, nor accepts optional arguments. It is useful, for example, to create a MGL script, which can later be post processed by another package like "listings".
-
-
‘mglblock’
-
It writes its contents verbatim to a file, specified as a mandatory argument, and to the LaTeX document, and numerates each line of code.
-
-
-
‘mglverbatim’
-
Exactly the same as ‘mglblock’, but it doesn’t write to a file. This environment doesn’t have arguments.
-
-
‘mglfunc’
-
Is used to define MGL functions. It takes one mandatory argument, which is the name of the function, plus one additional argument, which specifies the number of arguments of the function. The environment needs to contain only the body of the function, since the first and last lines are appended automatically, and the resulting code is written at the end of the general script, after the stop command, which is also written automatically. The warning is produced if 2 or more function with the same name is defined.
-
-
‘mglcomment’
-
Is used to contain multiline comments. This comments will be visible/invisible in the output document, depending on the use of the package options comments and nocomments (see above), or the \mglcomments and \mglnocomments commands (see bellow).
-
-
‘mglsetup’
-
If many scripts with the same code are to be written, the repetitive code can be written inside this environment only once, then this code will be used automatically every time the ‘\mglplot’ command is used (see below). It takes one optional argument, which is a name to be associated to the corresponding contents of the environment; this name can be passed to the ‘\mglplot’ command to use the corresponding block of code automatically (see below).
-
-
-
-
The package also defines the following commands:
-
-
‘\mglplot’
-
It takes one mandatory argument, which is MGL instructions separated by the symbol ‘:’ this argument can be more than one line long. It takes the same optional arguments as the ‘mgl’ environment, plus an additional argument setup, which indicates the name associated to a block of code inside a ‘mglsetup’ environment. The code inside the mandatory argument will be appended to the block of code specified, and the resulting code will be written to the general script.
-
-
An example of usage of ‘\mglplot’ command would be:
-
This command takes the same optional arguments as the ‘mgl’ environment, and one mandatory argument, which is the name of a MGL script. This command will compile the corresponding script and include the resulting image. It is useful when you have a script outside the LaTeX document, and you want to include the image, but you don’t want to type the script again.
-
-
‘\mglinclude’
-
This is like ‘\mglgraphics’ but, instead of creating/including the corresponding image, it writes the contents of the MGL script to the LaTeX document, and numerates the lines.
-
-
‘\mgldir’
-
This command can be used in the preamble of the document to specify a directory where LaTeX will save the MGL scripts and generate the corresponding images. This directory is also where ‘\mglgraphics’ and ‘\mglinclude’ will look for scripts.
-
-
‘\mglquality’
-
Adjust the quality of the MGL graphics produced similarly to quality.
-
-
‘\mgltexon, \mgltexoff’
-
Activate/deactivate the creation of MGL scripts and images. Notice these commands have local behavior in the sense that their effect is from the point they are called on.
-
-
‘\mglcomment, \mglnocomment’
-
Make visible/invisible the contents of the mglcomment environments. These commands have local effect too.
-
-
‘\mglTeX’
-
It just pretty prints the name of the package.
-
-
-
-
As an additional feature, when an image is not found or cannot be included, instead of issuing an error, mgltex prints a box with the word ‘MGL image not found’ in the LaTeX document.
-
Make one step for ordinary differential equation(s) {var1’ = eq1, ... } with time-step dt. Here strings eqs and vars contain the equations and variable names separated by symbol ‘;’. The variable(s) ‘var1’, ... are the ones, defined in MGL script previously. The Runge-Kutta 4-th order method is used.
-
UDAV (Universal Data Array Visualizator) is cross-platform program for data arrays visualization based on MathGL library. It support wide spectrum of graphics, simple script language and visual data handling and editing. It has window interface for data viewing, changing and plotting. Also it can execute MGL scripts, setup and rotate graphics and so on. UDAV hot-keys can be found in the appendix Hot-keys for UDAV.
-
UDAV have main window divided by 2 parts in general case and optional bottom panel(s). Left side contain tabs for MGL script and data arrays. Right side contain tabs with graphics itself, with list of variables and with help on MGL. Bottom side may contain the panel with MGL messages and warnings, and the panel with calculator.
-
-
-
-
Main window is shown on the figure above. You can see the script (at left) with current line highlighted by light-yellow, and result of its execution at right. Each panel have its own set of toolbuttons.
-
-
Editor toolbuttons allow: open and save script from/to file; undo and redo changes; cut, copy and paste selection; find/replace text; show dialogs for command arguments and for plot setup; show calculator at bottom.
-
-
Graphics toolbuttons allow: enable/disable additional transparency and lighting; show grid of absolute coordinates; enable mouse rotation; restore image view; refresh graphics (execute the script); stop calculation; copy graphics into clipboard; add primitives (line, curve, box, rhombus, ellipse, mark, text) to the image; change view angles manually. Vertical toolbuttons allow: shift and zoom in/out of image as whole; show next and previous frame of animation, or start animation (if one present).
-
-
Graphics panel support plot editing by mouse.
-
-
Axis range can be changed by mouse wheel or by dragging image by middle mouse button. Right button show popup menu. Left button show the coordinates of mouse click. At this double click will highlight plot under mouse and jump to the corresponded string of the MGL script.
-
Pressing "mouse rotation" toolbutton will change mouse actions: dragging by left button will rotate plot, middle button will shift the plot as whole, right button will zoom in/out plot as whole and add perspective, mouse wheel will zoom in/out plot as whole.
-
Manual primitives can be added by pressing corresponding toolbutton. They can be shifted as whole at any time by mouse dragging. At this double click open dialog with its properties. If toolbutton "grid of absolute coordinates" is pressed then editing of active points for primitives is enabled.
-
-
-
-
-
Short command description and list of its arguments are shown at the status-bar, when you move cursor to the new line of code. You can press F1 to see more detailed help on special panel.
-
-
-
-
Also you can look the current list of variables, its dimensions and its size in the memory (right side of above figure). Toolbuttons allow: create new variable, edit variable, delete variable, preview variable plot and its properties, refresh list of variables. Pressing on any column will sort table according its contents. Double click on a variable will open panel with data cells of the variable, where you can view/edit each cell independently or apply a set of transformations.
-
-
-
-
Finally, pressing F2 or F4 you can show/hide windows with messages/warnings and with calculator. Double click on a warning in message window will jump to corresponding line in editor. Calculator allow you type expression by keyboard as well as by toolbuttons. It know about all current variables, so you can use them in formulas.
-
There are a set of dialogs, which allow change/add a command, setup global plot properties, or setup UDAV itself.
-
-
-
-
One of most interesting dialog (hotkey Meta-C or Win-C) is dialog which help to enter new command or change arguments of existed one. It allows consequently select the category of command, command name in category and appropriate set of command arguments. At this right side show detailed command description. Required argument(s) are denoted by bold text. Strings are placed in apostrophes, like 'txt'. Buttons below table allow to call dialogs for changing style of command (if argument 'fmt' is present in the list of command arguments); to set variable or expression for argument(s); to add options for command. Note, you can click on a cell to enter value, or double-click to call corresponding dialog.
-
-
-
-
-
-
-
Dialog for changing style can be called independently, but usually is called from New command dialog or by double click on primitive. It contain 3 tabs: one for pen style, one for color scheme, one for text style. You should select appropriate one. Resulting string of style and sample picture are shown at bottom of dialog. Usually it can be called from New command dialog.
-
-
-
-
Dialog for entering variable allow to select variable or expression which can be used as argument of a command. Here you can select the variable name; range of indexes in each directions; operation which will be applied (like, summation, finding minimal/maximal values and so on). Usually it can be called from New command dialog.
-
-
-
-
Dialog for command options allow to change Command options. Usually it can be called from New command dialog.
-
-
-
-
-
-
Another interesting dialog, which help to select and properly setup a subplot, inplot, columnplot, stickplot and similar commands.
-
-
-
-
-
-
There is dialog for setting general plot properties, including tab for setting lighting properties. It can be called by called by hotkey ??? and put setup commands at the beginning of MGL script.
-
-
-
-
Also you can set or change script parameters (‘$0’ ... ‘$9’, see MGL definition).
-
-
-
-
Finally, there is dialog for UDAV settings. It allow to change most of things in UDAV appearance and working, including colors of keywords and numbers, default font and image size, and so on (see figure above).
-
-
There are also a set of dialogs for data handling, but they are too simple and clear. So, I will not put them here.
-
You can shift axis range by pressing middle button and moving mouse. Also, you can zoom in/out axis range by using mouse wheel.
-
You can rotate/shift/zoom whole plot by mouse. Just press ’Rotate’ toolbutton, click image and hold a mouse button: left button for rotation, right button for zoom/perspective, middle button for shift.
-
You may quickly draw the data from file. Just use: udav ’filename.dat’ in command line.
-
You can copy the current image to clipboard by pressing Ctrl-Shift-C. Later you can paste it directly into yours document or presentation.
-
You can export image into a set of format (EPS, SVG, PNG, JPEG) by pressing right mouse button inside image and selecting ’Export as ...’.
-
You can setup colors for script highlighting in Property dialog. Just select menu item ’Settings/Properties’.
-
You can save the parameter of animation inside MGL script by using comment started from ’##a ’ or ’##c ’ for loops.
-
New drawing never clears things drawn already. For example, you can make a surface with contour lines by calling commands ’surf’ and ’cont’ one after another (in any order).
-
You can put several plots in the same image by help of commands ’subplot’ or ’inplot’.
-
All indexes (of data arrays, subplots and so on) are always start from 0.
-
You can edit MGL file in any text editor. Also you can run it in console by help of commands: mglconv, mglview.
-
You can use command ’once on|off’ for marking the block which should be executed only once. For example, this can be the block of large data reading/creating/handling. Press F9 (or menu item ’Graphics/Reload’) to re-execute this block.
-
You can use command ’stop’ for terminating script parsing. It is useful if you don’t want to execute a part of script.
-
You can type arbitrary expression as input argument for data or number. In last case (for numbers), the first value of data array is used.
-
There is powerful calculator with a lot of special functions. You can use buttons or keyboard to type the expression. Also you can use existed variables in the expression.
-
The calculator can help you to put complex expression in the script. Just type the expression (which may depend on coordinates x,y,z and so on) and put it into the script.
-
You can easily insert file or folder names, last fitted formula or numerical value of selection by using menu Edit|Insert.
-
The special dialog (Edit|Insert|New Command) help you select the command, fill its arguments and put it into the script.
-
You can put several plotting commands in the same line or in separate function, for highlighting all of them simultaneously.
-
There are few end-user classes: mglGraph (see MathGL core), mglWindow and mglGLUT (see Widget classes), mglData (see Data processing), mglParse (see MGL scripts). Exactly these classes I recommend to use in most of user programs. All methods in all of these classes are inline and have exact C/Fortran analogue functions. This give compiler independent binary libraries for MathGL.
-
-
However, sometimes you may need to extend MathGL by writing yours own plotting functions or handling yours own data structures. In these cases you may need to use low-level API. This chapter describes it.
-
-
-
-
The internal structure of MathGL is rather complicated. There are C++ classes mglBase, mglCanvas, ... for drawing primitives and positioning the plot (blue ones in the figure). There is a layer of C functions, which include interface for most important methods of these classes. Also most of plotting functions are implemented as C functions. After it, there are “inline” front-end classes which are created for user convenience (yellow ones in the figure). Also there are widgets for FLTK and Qt libraries (green ones in the figure).
-
-
Below I show how this internal classes can be used.
-
Basically most of new kinds of plot can be created using just MathGL primitives (see Primitives). However the usage of mglBase methods can give you higher speed of drawing and better control of plot settings.
-
-
All plotting functions should use a pointer to mglBase class (or HMGL type in C functions) due to compatibility issues. Exactly such type of pointers are used in front-end classes (mglGraph, mglWindow) and in widgets (QMathGL, Fl_MathGL).
-
-
MathGL tries to remember all vertexes and all primitives and plot creation stage, and to use them for making final picture by demand. Basically for making plot, you need to add vertexes by AddPnt() function, which return index for new vertex, and call one of primitive drawing function (like mark_plot(), arrow_plot(), line_plot(), trig_plot(), quad_plot(), text_plot()), using vertex indexes as argument(s). AddPnt() function use 2 mreal numbers for color specification. First one is positioning in textures – integer part is texture index, fractional part is relative coordinate in the texture. Second number is like a transparency of plot (or second coordinate in the 2D texture).
-
-
I don’t want to put here detailed description of mglBase class. It was rather well documented in mgl2/base.h file. I just show and example of its usage on the base of circle drawing.
-
-
First, we should prototype new function circle() as C function.
-
First, we need to check all input arguments and send warnings if something is wrong. In our case it is negative value of r argument. We just send warning, since it is not critical situation – other plot still can be drawn.
-
Next step is creating a group. Group keep some general setting for plot (like options) and useful for export in 3d files.
-
static int cgid=1; gr->StartGroup("Circle",cgid++);
-
Now let apply options. Options are rather useful things, generally, which allow one easily redefine axis range(s), transparency and other settings (see Command options).
-
gr->SaveState(opt);
-
I use global setting for determining the number of points in circle approximation. Note, that user can change MeshNum by options easily.
-
const int n = gr->MeshNum>1?gr->MeshNum : 41;
-
Let try to determine plot specific flags. MathGL functions expect that most of flags will be sent in string. In our case it is symbol ‘@’ which set to draw filled circle instead of border only (last will be default). Note, you have to handle NULL as string pointer.
-
bool fill = mglchr(stl,'@');
-
Now, time for coloring. I use palette mechanism because circle have few colors: one for filling and another for border. SetPenPal() function parse input string and write resulting texture index in pal. Function return the character for marker, which can be specified in string str. Marker will be plotted at the center of circle. I’ll show on next sample how you can use color schemes (smooth colors) too.
-
long pal=0;
- char mk=gr->SetPenPal(stl,&pal);
-
Next step, is determining colors for filling and for border. First one for filling.
-
mreal c=gr->NextColor(pal), d;
-
Second one for border. I use black color (call gr->AddTexture('k')) if second color is not specified.
-
If user want draw only border (fill=false) then I use first color for border.
-
if(!fill) k=c;
-
Now we should reserve space for vertexes. This functions need n for border, n+1 for filling and 1 for marker. So, maximal number of vertexes is 2*n+2. Note, that such reservation is not required for normal work but can sufficiently speed up the plotting.
-
gr->Reserve(2*n+2);
-
We’ve done with setup and ready to start drawing. First, we need to add vertex(es). Let define NAN as normals, since I don’t want handle lighting for this plot,
-
mglPoint q(NAN,NAN);
-
and start adding vertexes. First one for central point of filling. I use -1 if I don’t need this point. The arguments of AddPnt() function is: mglPoint(x,y,z) – coordinate of vertex, c – vertex color, q – normal at vertex, -1 – vertex transparency (-1 for default), 3 bitwise flag which show that coordinates will be scaled (0x1) and will not be cutted (0x2).
-
long n0,n1,n2,m1,m2,i;
- n0 = fill ? gr->AddPnt(mglPoint(x,y,z),c,q,-1,3):-1;
-
Similar for marker, but we use different color k.
-
Time for drawing circle itself. I use -1 for m1, n1 as sign that primitives shouldn’t be drawn for first point i=0.
-
for(i=0,m1=n1=-1;i<n;i++)
- {
-
Each function should check Stop variable and return if it is non-zero. It is done for interrupting drawing for system which don’t support multi-threading.
-
if(gr->Stop) return;
-
Let find coordinates of vertex.
-
mreal t = i*2*M_PI/(n-1.);
- mglPoint p(x+r*cos(t), y+r*sin(t), z);
-
Save previous vertex and add next one
-
n2 = n1; n1 = gr->AddPnt(p,c,q,-1,3);
-
and copy it for border but with different color. Such copying is much faster than adding new vertex using AddPnt().
-
m2 = m1; m1 = gr->CopyNtoC(n1,k);
-
Now draw triangle for filling internal part
-
if(fill) gr->trig_plot(n0,n1,n2);
-
and draw line for border.
-
gr->line_plot(m1,m2);
- }
-
Drawing is done. Let close group and return.
-
gr->EndGroup();
-}
-
-
Another sample I want to show is exactly the same function but with smooth coloring using color scheme. So, I’ll add comments only in the place of difference.
-
In this case let allow negative radius too. Formally it is not the problem for plotting (formulas the same) and this allow us to handle all color range.
-
//if(r<=0) { gr->SetWarn(mglWarnNeg,"Circle"); return; }
-
- static int cgid=1; gr->StartGroup("CircleCS",cgid++);
- gr->SaveState(opt);
- const int n = gr->MeshNum>1?gr->MeshNum : 41;
- bool fill = mglchr(stl,'@');
-
Here is main difference. We need to create texture for color scheme specified by user
-
long ss = gr->AddTexture(stl);
-
But we need also get marker and color for it (if filling is enabled). Let suppose that marker and color is specified after ‘:’. This is standard delimiter which stop color scheme entering. So, just lets find it and use for setting pen.
-
The last thing which we can do is derive our own class with new plotting functions. Good idea is to derive it from mglGraph (if you don’t need extended window), or from mglWindow (if you need to extend window). So, in our case it will be
-
mglData class have abstract predecessor class mglDataA. Exactly the pointers to mglDataA instances are used in all plotting functions and some of data processing functions. This was done for taking possibility to define yours own class, which will handle yours own data (for example, complex numbers, or differently organized data). And this new class will be almost the same as mglData for plotting purposes.
-
-
However, the most of data processing functions will be slower as if you used mglData instance. This is more or less understandable – I don’t know how data in yours particular class will be organized, and couldn’t optimize the these functions generally.
-
-
There are few virtual functions which must be provided in derived classes. This functions give:
-
-
the sizes of the data (GetNx, GetNy, GetNz),
-
give data value and numerical derivatives for selected cell (v, dvx, dvy, dvz),
-
give maximal and minimal values (Maximal, Minimal) – you can use provided functions (like mgl_data_max and mgl_data_min), but yours own realization can be more efficient,
-
give access to all element as in single array (vthr) – you need this only if you want using MathGL’s data processing functions.
-
-
-
Let me, for example define class mglComplex which will handle complex number and draw its amplitude or phase, depending on flag use_abs:
-
#include <complex>
-#include <mgl2/mgl.h>
-#define dual std::complex<double>
-class mglComplex : public mglDataA
-{
-public:
- long nx; ///< number of points in 1st dimensions ('x' dimension)
- long ny; ///< number of points in 2nd dimensions ('y' dimension)
- long nz; ///< number of points in 3d dimensions ('z' dimension)
- dual *a; ///< data array
- bool use_abs; ///< flag to use abs() or arg()
-
- inline mglComplex(long xx=1,long yy=1,long zz=1)
- { a=0; use_abs=true; Create(xx,yy,zz); }
- virtual ~mglComplex() { if(a) delete []a; }
-
- /// Get sizes
- inline long GetNx() const { return nx; }
- inline long GetNy() const { return ny; }
- inline long GetNz() const { return nz; }
- /// Create or recreate the array with specified size and fill it by zero
- inline void Create(long mx,long my=1,long mz=1)
- { nx=mx; ny=my; nz=mz; if(a) delete []a;
- a = new dual[nx*ny*nz]; }
- /// Get maximal value of the data
- inline mreal Maximal() const { return mgl_data_max(this); }
- /// Get minimal value of the data
- inline mreal Minimal() const { return mgl_data_min(this); }
-
-protected:
- inline mreal v(long i,long j=0,long k=0) const
- { return use_abs ? abs(a[i+nx*(j+ny*k)]) : arg(a[i+nx*(j+ny*k)]); }
- inline mreal vthr(long i) const
- { return use_abs ? abs(a[i]) : arg(a[i]); }
- inline mreal dvx(long i,long j=0,long k=0) const
- { long i0=i+nx*(j+ny*k);
- std::complex<double> res=i>0? (i<nx-1? (a[i0+1]-a[i0-1])/2.:a[i0]-a[i0-1]) : a[i0+1]-a[i0];
- return use_abs? abs(res) : arg(res); }
- inline mreal dvy(long i,long j=0,long k=0) const
- { long i0=i+nx*(j+ny*k);
- std::complex<double> res=j>0? (j<ny-1? (a[i0+nx]-a[i0-nx])/2.:a[i0]-a[i0-nx]) : a[i0+nx]-a[i0];
- return use_abs? abs(res) : arg(res); }
- inline mreal dvz(long i,long j=0,long k=0) const
- { long i0=i+nx*(j+ny*k), n=nx*ny;
- std::complex<double> res=k>0? (k<nz-1? (a[i0+n]-a[i0-n])/2.:a[i0]-a[i0-n]) : a[i0+n]-a[i0];
- return use_abs? abs(res) : arg(res); }
-};
-int main()
-{
- mglComplex dat(20);
- for(long i=0;i<20;i++)
- dat.a[i] = 3*exp(-0.05*(i-10)*(i-10))*dual(cos(M_PI*i*0.3), sin(M_PI*i*0.3));
- mglGraph gr;
- gr.SetRange('y', -M_PI, M_PI); gr.Box();
-
- gr.Plot(dat,"r","legend 'abs'");
- dat.use_abs=false;
- gr.Plot(dat,"b","legend 'arg'");
- gr.Legend();
- gr.WritePNG("complex.png");
- return 0;
-}
-
Structure for working with colors. This structure is defined in #include <mgl2/type.h>.
-
-
There are two ways to set the color in MathGL. First one is using of mreal values of red, green and blue channels for precise color definition. The second way is the using of character id. There are a set of characters specifying frequently used colors. Normally capital letter gives more dark color than lowercase one. See Line styles.
-
Function axial draw surfaces of rotation for contour lines. You can draw wire surfaces (‘#’ style) or ones rotated in other directions (‘x’, ‘z’ styles).
-
Function bars draw vertical bars. It have a lot of options: bar-above-bar (‘a’ style), fall like (‘f’ style), 2 colors for positive and negative values, wired bars (‘#’ style), 3D variant.
-
Function candle draw candlestick chart. This is a combination of a line-chart and a bar-chart, in that each bar represents the range of price movement over a given time interval.
-
-
MGL code:
-
new y 30 'sin(pi*x/2)^2'
-subplot 1 1 0 '':title 'Candle plot (default)'
-yrange 0 1:box
-candle y y/2 (y+1)/2
-
Function chart draw colored boxes with width proportional to data values. Use ‘’ for empty box. It produce well known pie chart if drawn in polar coordinates.
-
Function cloud draw cloud-like object which is less transparent for higher data values. Similar plot can be created using many (about 10...20 – surf3a a a;value 10) isosurfaces surf3a.
-
call 'prepare2v'
-call 'prepare3d'
-new v 10:fill v -0.5 1:copy d sqrt(a^2+b^2)
-subplot 2 2 0:title 'Surf + Cont':rotate 50 60:light on:box:surf a:cont a 'y'
-subplot 2 2 1 '':title 'Flow + Dens':light off:box:flow a b 'br':dens d
-subplot 2 2 2:title 'Mesh + Cont':rotate 50 60:box:mesh a:cont a '_'
-subplot 2 2 3:title 'Surf3 + ContF3':rotate 50 60:light on
-box:contf3 v c 'z' 0:contf3 v c 'x':contf3 v c
-cut 0 -1 -1 1 0 1.1
-contf3 v c 'z' c.nz-1:surf3 c -0.5
-
Function cont draw contour lines for surface. You can select automatic (default) or manual levels for contours, print contour labels, draw it on the surface (default) or at plane (as Dens).
-
-
MGL code:
-
call 'prepare2d'
-list v -0.5 -0.15 0 0.15 0.5
-subplot 2 2 0:title 'Cont plot (default)':rotate 50 60:box:cont a
-subplot 2 2 1:title 'manual levels':rotate 50 60:box:cont v a
-subplot 2 2 2:title '"\_" and "." styles':rotate 50 60:box:cont a '_':cont a '_.2k'
-subplot 2 2 3 '':title '"t" style':box:cont a 't'
-
Functions contz, conty, contx draw contour lines on plane perpendicular to corresponding axis. One of possible application is drawing projections of 3D field.
-
-
MGL code:
-
call 'prepare3d'
-title 'Cont[XYZ] sample':rotate 50 60:box
-contx {sum c 'x'} '' -1:conty {sum c 'y'} '' 1:contz {sum c 'z'} '' -1
-
Functions contfz, contfy, contfx, draw filled contours on plane perpendicular to corresponding axis. One of possible application is drawing projections of 3D field.
-
-
MGL code:
-
call 'prepare3d'
-title 'ContF[XYZ] sample':rotate 50 60:box
-contfx {sum c 'x'} '' -1:contfy {sum c 'y'} '' 1:contfz {sum c 'z'} '' -1
-
new a 100 'exp(-10*x^2)'
-new b 100 'exp(-10*(x+0.5)^2)'
-yrange 0 1
-subplot 1 2 0 '_':title 'Input fields'
-plot a:plot b:box:axis
-correl r a b 'x'
-norm r 0 1:swap r 'x' # make it human readable
-subplot 1 2 1 '_':title 'Correlation of a and b'
-plot r 'r':axis:box
-line 0.5 0 0.5 1 'B|'
-
-
C++ code:
-
void smgl_correl(mglGraph *gr)
-{
- mglData a(100),b(100);
- gr->Fill(a,"exp(-10*x^2)"); gr->Fill(b,"exp(-10*(x+0.5)^2)");
- gr->SetRange('y',0,1);
- gr->SubPlot(1,2,0,"_"); gr->Title("Input fields");
- gr->Plot(a); gr->Plot(b); gr->Axis(); gr->Box();
- mglData r = a.Correl(b,"x");
- r.Norm(0,1); r.Swap("x"); // make it human readable
- gr->SubPlot(1,2,1,"_"); gr->Title("Correlation of a and b");
- gr->Plot(r,"r"); gr->Axis(); gr->Box();
- gr->Line(mglPoint(0.5,0),mglPoint(0.5,1),"B|");
-}
-
new a 40 50 60 'exp(-x^2-4*y^2-16*z^2)'
-light on:alpha on
-copy b a:diff b 'x':subplot 5 3 0:call 'splot'
-copy b a:diff2 b 'x':subplot 5 3 1:call 'splot'
-copy b a:cumsum b 'x':subplot 5 3 2:call 'splot'
-copy b a:integrate b 'x':subplot 5 3 3:call 'splot'
-mirror b 'x':subplot 5 3 4:call 'splot'
-copy b a:diff b 'y':subplot 5 3 5:call 'splot'
-copy b a:diff2 b 'y':subplot 5 3 6:call 'splot'
-copy b a:cumsum b 'y':subplot 5 3 7:call 'splot'
-copy b a:integrate b 'y':subplot 5 3 8:call 'splot'
-mirror b 'y':subplot 5 3 9:call 'splot'
-copy b a:diff b 'z':subplot 5 3 10:call 'splot'
-copy b a:diff2 b 'z':subplot 5 3 11:call 'splot'
-copy b a:cumsum b 'z':subplot 5 3 12:call 'splot'
-copy b a:integrate b 'z':subplot 5 3 13:call 'splot'
-mirror b 'z':subplot 5 3 14:call 'splot'
-stop
-func splot 0
-title 'max=',b.max:norm b -1 1 on:rotate 70 60:box:surf3 b
-return
-
new a 40 50 60 'exp(-x^2-4*y^2-16*z^2)'
-light on:alpha on
-copy b a:sinfft b 'x':subplot 5 3 0:call 'splot'
-copy b a:cosfft b 'x':subplot 5 3 1:call 'splot'
-copy b a:hankel b 'x':subplot 5 3 2:call 'splot'
-copy b a:swap b 'x':subplot 5 3 3:call 'splot'
-copy b a:smooth b 'x':subplot 5 3 4:call 'splot'
-copy b a:sinfft b 'y':subplot 5 3 5:call 'splot'
-copy b a:cosfft b 'y':subplot 5 3 6:call 'splot'
-copy b a:hankel b 'y':subplot 5 3 7:call 'splot'
-copy b a:swap b 'y':subplot 5 3 8:call 'splot'
-copy b a:smooth b 'y':subplot 5 3 9:call 'splot'
-copy b a:sinfft b 'z':subplot 5 3 10:call 'splot'
-copy b a:cosfft b 'z':subplot 5 3 11:call 'splot'
-copy b a:hankel b 'z':subplot 5 3 12:call 'splot'
-copy b a:swap b 'z':subplot 5 3 13:call 'splot'
-copy b a:smooth b 'z':subplot 5 3 14:call 'splot'
-stop
-func splot 0
-title 'max=',b.max:norm b -1 1 on:rotate 70 60:box
-surf3 b 0.5:surf3 b -0.5
-return
-
Functions densz, densy, densx draw density plot on plane perpendicular to corresponding axis. One of possible application is drawing projections of 3D field.
-
-
MGL code:
-
call 'prepare3d'
-title 'Dens[XYZ] sample':rotate 50 60:box
-densx {sum c 'x'} '' -1:densy {sum c 'y'} '' 1:densz {sum c 'z'} '' -1
-
define n 32 #number of points
-define m 20 # number of iterations
-define dt 0.01 # time step
-new res n m+1
-ranges -1 1 0 m*dt 0 1
-
-#tridmat periodic variant
-new !a n 'i',dt*(n/2)^2/2
-copy !b !(1-2*a)
-
-new !u n 'exp(-6*x^2)'
-put res u all 0
-for $i 0 m
-tridmat u a b a u 'xdc'
-put res u all $i+1
-next
-subplot 2 2 0 '<_':title 'Tridmat, periodic b.c.'
-axis:box:dens res
-
-#fourier variant
-new k n:fillsample k 'xk'
-copy !e !exp(-i1*dt*k^2)
-
-new !u n 'exp(-6*x^2)'
-put res u all 0
-for $i 0 m
-fourier u 'x'
-multo u e
-fourier u 'ix'
-put res u all $i+1
-next
-subplot 2 2 1 '<_':title 'Fourier method'
-axis:box:dens res
-
-#tridmat zero variant
-new !u n 'exp(-6*x^2)'
-put res u all 0
-for $i 0 m
-tridmat u a b a u 'xd'
-put res u all $i+1
-next
-subplot 2 2 2 '<_':title 'Tridmat, zero b.c.'
-axis:box:dens res
-
-#diffract exp variant
-new !u n 'exp(-6*x^2)'
-define q dt*(n/2)^2/8 # need q<0.4 !!!
-put res u all 0
-for $i 0 m
-for $j 1 8 # due to smaller dt
-diffract u 'xe' q
-next
-put res u all $i+1
-next
-subplot 2 2 3 '<_':title 'Diffract, exp b.c.'
-axis:box:dens res
-
Function dots is another way to draw irregular points. Dots use color scheme for coloring (see Color scheme).
-
-
MGL code:
-
new t 2000 'pi*(rnd-0.5)':new f 2000 '2*pi*rnd'
-copy x 0.9*cos(t)*cos(f):copy y 0.9*cos(t)*sin(f):copy z 0.6*sin(t):copy c cos(2*t)
-subplot 2 2 0:title 'Dots sample':rotate 50 60
-box:dots x y z
-alpha on
-subplot 2 2 1:title 'add transparency':rotate 50 60
-box:dots x y z c
-subplot 2 2 2:title 'add colorings':rotate 50 60
-box:dots x y z x c
-subplot 2 2 3:title 'Only coloring':rotate 50 60
-box:tens x y z x ' .'
-
import dat 'Equirectangular-projection.jpg' 'BbGYw' -1 1
-subplot 1 1 0 '<>':title 'Earth in 3D':rotate 40 60
-copy phi dat 'pi*x':copy tet dat 'pi*y/2'
-copy x cos(tet)*cos(phi)
-copy y cos(tet)*sin(phi)
-copy z sin(tet)
-
-light on
-surfc x y z dat 'BbGYw'
-contp [-0.51,-0.51] x y z dat 'y'
-
Function error draw error boxes around the points. You can draw default boxes or semi-transparent symbol (like marker, see Line styles). Also you can set individual color for each box. See also error2 sample.
-
new a 100 100 'x^2*y':new b 100 100
-export a 'test_data.png' 'BbcyrR' -1 1
-import b 'test_data.png' 'BbcyrR' -1 1
-subplot 2 1 0 '':title 'initial':box:dens a
-subplot 2 1 1 '':title 'imported':box:dens b
-
Function fall draw waterfall surface. You can use meshnum for changing number of lines to be drawn. Also you can use ‘x’ style for drawing lines in other direction.
-
-
MGL code:
-
call 'prepare2d'
-title 'Fall plot':rotate 50 60:box:fall a
-
new dat 100 '0.4*rnd+0.1+sin(2*pi*x)'
-new in 100 '0.3+sin(2*pi*x)'
-list ini 1 1 3:fit res dat 'a+b*sin(c*x)' 'abc' ini
-title 'Fitting sample':yrange -2 2:box:axis:plot dat 'k. '
-plot res 'r':plot in 'b'
-text -0.9 -1.3 'fitted:' 'r:L'
-putsfit 0 -1.8 'y = ' 'r':text 0 2.2 'initial: y = 0.3+sin(2\pi x)' 'b'
-
Function flame2d generate points for flame fractals in 2d case.
-
-
MGL code:
-
list A [0.33,0,0,0.33,0,0,0.2] [0.33,0,0,0.33,0.67,0,0.2] [0.33,0,0,0.33,0.33,0.33,0.2]\
- [0.33,0,0,0.33,0,0.67,0.2] [0.33,0,0,0.33,0.67,0.67,0.2]
-new B 2 3 A.ny '0.3'
-put B 3 0 0 -1
-put B 3 0 1 -1
-put B 3 0 2 -1
-flame2d fx fy A B 1000000
-subplot 1 1 0 '<_':title 'Flame2d sample'
-ranges fx fy:box:axis
-plot fx fy 'r#o ';size 0.05
-
Function flow is another standard way to visualize vector fields – it draw lines (threads) which is tangent to local vector field direction. MathGL draw threads from edges of bounding box and from central slices. Sometimes it is not most appropriate variant – you may want to use flowp to specify manual position of threads. The color scheme is used for coloring (see Color scheme). At this warm color corresponds to normal flow (like attractor), cold one corresponds to inverse flow (like source).
-
-
MGL code:
-
call 'prepare2v'
-call 'prepare3v'
-subplot 2 2 0 '':title 'Flow plot (default)':box:flow a b
-subplot 2 2 1 '':title '"v" style':box:flow a b 'v'
-subplot 2 2 2 '':title '"#" and "." styles':box:flow a b '#':flow a b '.2k'
-subplot 2 2 3:title '3d variant':rotate 50 60:box:flow ex ey ez
-
Function flow3 draw flow threads, which start from given plane.
-
-
MGL code:
-
call 'prepare3v'
-subplot 2 2 0:title 'Flow3 plot (default)':rotate 50 60:box
-flow3 ex ey ez
-subplot 2 2 1:title '"v" style, from boundary':rotate 50 60:box
-flow3 ex ey ez 'v' 0
-subplot 2 2 2:title '"t" style':rotate 50 60:box
-flow3 ex ey ez 't' 0
-subplot 2 2 3:title 'from \i z planes':rotate 50 60:box
-flow3 ex ey ez 'z' 0
-flow3 ex ey ez 'z' 9
-
subplot 1 1 0 '':title 'SubData vs Evaluate'
-new in 9 'x^3/1.1':plot in 'ko ':box
-new arg 99 '4*x+4'
-evaluate e in arg off:plot e 'b.'; legend 'Evaluate'
-subdata s in arg:plot s 'r.';legend 'SubData'
-legend 2
-
-
C++ code:
-
void smgl_indirect(mglGraph *gr)
-{
- gr->SubPlot(1,1,0,""); gr->Title("SubData vs Evaluate");
- mglData in(9), arg(99), e, s;
- gr->Fill(in,"x^3/1.1"); gr->Fill(arg,"4*x+4");
- gr->Plot(in,"ko "); gr->Box();
- e = in.Evaluate(arg,false); gr->Plot(e,"b.","legend 'Evaluate'");
- s = in.SubData(arg); gr->Plot(s,"r.","legend 'SubData'");
- gr->Legend(2);
-}
-
Function ohlc draw Open-High-Low-Close diagram. This diagram show vertical line for between maximal(high) and minimal(low) values, as well as horizontal lines before/after vertical line for initial(open)/final(close) values of some process.
-
-
MGL code:
-
new o 10 '0.5*sin(pi*x)'
-new c 10 '0.5*sin(pi*(x+2/9))'
-new l 10 '0.3*rnd-0.8'
-new h 10 '0.3*rnd+0.5'
-subplot 1 1 0 '':title 'OHLC plot':box:ohlc o h l c
-
new x 100 'sin(pi*x)'
-new y 100 'cos(pi*x)'
-new z 100 'sin(2*pi*x)'
-new c 100 'cos(2*pi*x)'
-
-subplot 4 3 0:rotate 40 60:box:plot x y z
-subplot 4 3 1:rotate 40 60:box:area x y z
-subplot 4 3 2:rotate 40 60:box:tens x y z c
-subplot 4 3 3:rotate 40 60:box:bars x y z
-subplot 4 3 4:rotate 40 60:box:stem x y z
-subplot 4 3 5:rotate 40 60:box:textmark x y z c*2 '\alpha'
-subplot 4 3 6:rotate 40 60:box:tube x y z c/10
-subplot 4 3 7:rotate 40 60:box:mark x y z c 's'
-subplot 4 3 8:box:error x y z/10 c/10
-subplot 4 3 9:rotate 40 60:box:step x y z
-subplot 4 3 10:rotate 40 60:box:torus x z 'z';light on
-subplot 4 3 11:rotate 40 60:box:label x y z '%z'
-
new x 100 100 'sin(pi*(x+y)/2)*cos(pi*y/2)'
-new y 100 100 'cos(pi*(x+y)/2)*cos(pi*y/2)'
-new z 100 100 'sin(pi*y/2)'
-new c 100 100 'cos(pi*x)'
-
-subplot 4 4 0:rotate 40 60:box:surf x y z
-subplot 4 4 1:rotate 40 60:box:surfc x y z c
-subplot 4 4 2:rotate 40 60:box:surfa x y z c;alpha 1
-subplot 4 4 3:rotate 40 60:box:mesh x y z;meshnum 10
-subplot 4 4 4:rotate 40 60:box:tile x y z;meshnum 10
-subplot 4 4 5:rotate 40 60:box:tiles x y z c;meshnum 10
-subplot 4 4 6:rotate 40 60:box:axial x y z;alpha 0.5;light on
-subplot 4 4 7:rotate 40 60:box:cont x y z
-subplot 4 4 8:rotate 40 60:box:contf x y z;light on:contv x y z;light on
-subplot 4 4 9:rotate 40 60:box:belt x y z 'x';meshnum 10;light on
-subplot 4 4 10:rotate 40 60:box:dens x y z;alpha 0.5
-subplot 4 4 11:rotate 40 60:box
-fall x y z 'g';meshnum 10:fall x y z 'rx';meshnum 10
-subplot 4 4 12:rotate 40 60:box:belt x y z '';meshnum 10;light on
-subplot 4 4 13:rotate 40 60:box:boxs x y z '';meshnum 10;light on
-subplot 4 4 14:rotate 40 60:box:boxs x y z '#';meshnum 10;light on
-subplot 4 4 15:rotate 40 60:box:boxs x y z '@';meshnum 10;light on
-
new x 50 50 50 '(x+2)/3*sin(pi*y/2)'
-new y 50 50 50 '(x+2)/3*cos(pi*y/2)'
-new z 50 50 50 'z'
-new c 50 50 50 '-2*(x^2+y^2+z^4-z^2)+0.2'
-new d 50 50 50 '1-2*tanh(2*(x+y)^2)'
-
-alpha on:light on
-subplot 4 3 0:rotate 40 60:box:surf3 x y z c
-subplot 4 3 1:rotate 40 60:box:surf3c x y z c d
-subplot 4 3 2:rotate 40 60:box:surf3a x y z c d
-subplot 4 3 3:rotate 40 60:box:cloud x y z c
-subplot 4 3 4:rotate 40 60:box:cont3 x y z c:cont3 x y z c 'x':cont3 x y z c 'z'
-subplot 4 3 5:rotate 40 60:box:contf3 x y z c:contf3 x y z c 'x':contf3 x y z c 'z'
-subplot 4 3 6:rotate 40 60:box:dens3 x y z c:dens3 x y z c 'x':dens3 x y z c 'z'
-subplot 4 3 7:rotate 40 60:box:dots x y z c;meshnum 15
-subplot 4 3 8:rotate 40 60:box:densx c '' 0:densy c '' 0:densz c '' 0
-subplot 4 3 9:rotate 40 60:box:contx c '' 0:conty c '' 0:contz c '' 0
-subplot 4 3 10:rotate 40 60:box:contfx c '' 0:contfy c '' 0:contfz c '' 0
-
new x 20 20 20 '(x+2)/3*sin(pi*y/2)'
-new y 20 20 20 '(x+2)/3*cos(pi*y/2)'
-new z 20 20 20 'z+x'
-new ex 20 20 20 'x'
-new ey 20 20 20 'x^2+y'
-new ez 20 20 20 'y^2+z'
-
-new x1 50 50 '(x+2)/3*sin(pi*y/2)'
-new y1 50 50 '(x+2)/3*cos(pi*y/2)'
-new e1 50 50 'x'
-new e2 50 50 'x^2+y'
-
-subplot 3 3 0:rotate 40 60:box:vect x1 y1 e1 e2
-subplot 3 3 1:rotate 40 60:box:flow x1 y1 e1 e2
-subplot 3 3 2:rotate 40 60:box:pipe x1 y1 e1 e2
-subplot 3 3 3:rotate 40 60:box:dew x1 y1 e1 e2
-subplot 3 3 4:rotate 40 60:box:vect x y z ex ey ez
-subplot 3 3 5:rotate 40 60:box
-vect3 x y z ex ey ez:vect3 x y z ex ey ez 'x':vect3 x y z ex ey ez 'z'
-grid3 x y z z '{r9}':grid3 x y z z '{g9}x':grid3 x y z z '{b9}z'
-subplot 3 3 6:rotate 40 60:box:flow x y z ex ey ez
-subplot 3 3 7:rotate 40 60:box:pipe x y z ex ey ez
-
new re 128 'exp(-48*(x+0.7)^2)':new im 128
-pde a 'p^2+q^2-x-1+i*0.5*(z+x)*(z>-x)' re im 0.01 30
-transpose a
-subplot 1 1 0 '<_':title 'PDE solver'
-axis:xlabel '\i x':ylabel '\i z'
-crange 0 1:dens a 'wyrRk'
-fplot '-x' 'k|'
-text 0 0.95 'Equation: ik_0\partial_zu + \Delta u + x\cdot u + i \frac{x+z}{2}\cdot u = 0\n{}absorption: (x+z)/2 for x+z>0'
-
-
C++ code:
-
void smgl_pde(mglGraph *gr) // PDE sample
-{
- mglData a,re(128),im(128);
- gr->Fill(re,"exp(-48*(x+0.7)^2)");
- a = gr->PDE("p^2+q^2-x-1+i*0.5*(z+x)*(z>-x)", re, im, 0.01, 30);
- a.Transpose("yxz");
- if(big!=3) {gr->SubPlot(1,1,0,"<_"); gr->Title("PDE solver"); }
- gr->SetRange('c',0,1); gr->Dens(a,"wyrRk");
- gr->Axis(); gr->Label('x', "\\i x"); gr->Label('y', "\\i z");
- gr->FPlot("-x", "k|");
- gr->Puts(mglPoint(0, 0.95), "Equation: ik_0\\partial_zu + \\Delta u + x\\cdot u + i \\frac{x+z}{2}\\cdot u = 0\nabsorption: (x+z)/2 for x+z>0");
-}
-
Function pipe is similar to flow but draw pipes (tubes) which radius is proportional to the amplitude of vector field. The color scheme is used for coloring (see Color scheme). At this warm color corresponds to normal flow (like attractor), cold one corresponds to inverse flow (like source).
-
-
MGL code:
-
call 'prepare2v'
-call 'prepare3v'
-subplot 2 2 0 '':title 'Pipe plot (default)':light on:box:pipe a b
-subplot 2 2 1 '':title '"i" style':box:pipe a b 'i'
-subplot 2 2 2 '':title 'from edges only':box:pipe a b '#'
-subplot 2 2 3:title '3d variant':rotate 50 60:box:pipe ex ey ez '' 0.1
-
Function plot is most standard way to visualize 1D data array. By default, Plot use colors from palette. However, you can specify manual color/palette, and even set to use new color for each points by using ‘!’ style. Another feature is ‘’ style which draw only markers without line between points.
-
Function pmap draw Poincare map – show intersections of the curve and the surface.
-
-
MGL code:
-
subplot 1 1 0 '<_^':title 'Poincare map sample'
-ode r 'cos(y)+sin(z);cos(z)+sin(x);cos(x)+sin(y)' 'xyz' [0.1,0,0] 0.1 100
-rotate 40 60:copy x r(0):copy y r(1):copy z r(2)
-ranges x y z
-axis:plot x y z 'b'
-xlabel '\i x' 0:ylabel '\i y' 0:zlabel '\i z'
-pmap x y z z 'b#o'
-fsurf '0'
-
ranges 0 1 0 1 0 1
-new x 50 '0.25*(1+cos(2*pi*x))'
-new y 50 '0.25*(1+sin(2*pi*x))'
-new z 50 'x'
-new a 20 30 '30*x*y*(1-x-y)^2*(x+y<1)'
-new rx 10 'rnd':new ry 10:fill ry '(1-v)*rnd' rx
-light on
-
-title 'Projection sample':ternary 4:rotate 50 60
-box:axis:grid
-plot x y z 'r2':surf a '#'
-xlabel 'X':ylabel 'Y':zlabel 'Z'
-
The radar plot is variant of plot, which make plot in polar coordinates and draw radial rays in point directions. If you just need a plot in polar coordinates then I recommend to use Curvilinear coordinates or plot in parametric form with x=r*cos(fi); y=r*sin(fi);.
-
-
MGL code:
-
new yr 10 3 '0.4*sin(pi*(x+1.5+y/2)+0.1*rnd)'
-subplot 1 1 0 '':title 'Radar plot (with grid, "\#")':radar yr '#'
-
new x 10 '0.5+rnd':cumsum x 'x':norm x -1 1
-copy y sin(pi*x)/1.5
-subplot 2 2 0 '<_':title 'Refill sample'
-box:axis:plot x y 'o ':fplot 'sin(pi*x)/1.5' 'B:'
-new r 100:refill r x y:plot r 'r'
-
-subplot 2 2 1 '<_':title 'Global spline'
-box:axis:plot x y 'o ':fplot 'sin(pi*x)/1.5' 'B:'
-new r 100:gspline r x y:plot r 'r'
-
-new y 10 '0.5+rnd':cumsum y 'x':norm y -1 1
-copy xx x:extend xx 10
-copy yy y:extend yy 10:transpose yy
-copy z sin(pi*xx*yy)/1.5
-alpha on:light on
-subplot 2 2 2:title '2d regular':rotate 40 60
-box:axis:mesh xx yy z 'k'
-new rr 100 100:refill rr x y z:surf rr
-
-new xx 10 10 '(x+1)/2*cos(y*pi/2-1)':new yy 10 10 '(x+1)/2*sin(y*pi/2-1)'
-copy z sin(pi*xx*yy)/1.5
-subplot 2 2 3:title '2d non-regular':rotate 40 60
-box:axis:plot xx yy z 'ko '
-new rr 100 100:refill rr xx yy z:surf rr
-
Function region fill the area between 2 curves. It support gradient filling if 2 colors per curve is specified. Also it can fill only the region y1<y<y2 if style ‘i’ is used.
-
zrange 0 1
-new x 20 30 '(x+2)/3*cos(pi*y)'
-new y 20 30 '(x+2)/3*sin(pi*y)'
-new z 20 30 'exp(-6*x^2-2*sin(pi*y)^2)'
-
-subplot 2 1 0:title 'Cartesian space':rotate 30 -40
-axis 'xyzU':box
-xlabel 'x':ylabel 'y'
-origin 1 1:grid 'xy'
-mesh x y z
-
-# section along 'x' direction
-solve u x 0.5 'x'
-var v u.nx 0 1
-evaluate yy y u v
-evaluate xx x u v
-evaluate zz z u v
-plot xx yy zz 'k2o'
-
-# 1st section along 'y' direction
-solve u1 x -0.5 'y'
-var v1 u1.nx 0 1
-evaluate yy y v1 u1
-evaluate xx x v1 u1
-evaluate zz z v1 u1
-plot xx yy zz 'b2^'
-
-# 2nd section along 'y' direction
-solve u2 x -0.5 'y' u1
-evaluate yy y v1 u2
-evaluate xx x v1 u2
-evaluate zz z v1 u2
-plot xx yy zz 'r2v'
-
-subplot 2 1 1:title 'Accompanied space'
-ranges 0 1 0 1:origin 0 0
-axis:box:xlabel 'i':ylabel 'j':grid2 z 'h'
-
-plot u v 'k2o':line 0.4 0.5 0.8 0.5 'kA'
-plot v1 u1 'b2^':line 0.5 0.15 0.5 0.3 'bA'
-plot v1 u2 'r2v':line 0.5 0.7 0.5 0.85 'rA'
-
Function surf is most standard way to visualize 2D data array. Surf use color scheme for coloring (see Color scheme). You can use ‘#’ style for drawing black meshes on the surface.
-
-
MGL code:
-
call 'prepare2d'
-subplot 2 2 0:title 'Surf plot (default)':rotate 50 60:light on:box:surf a
-subplot 2 2 1:title '"\#" style; meshnum 10':rotate 50 60:box:surf a '#'; meshnum 10
-subplot 2 2 2:title '"." style':rotate 50 60:box:surf a '.'
-new x 50 40 '0.8*sin(pi*x)*sin(pi*(y+1)/2)'
-new y 50 40 '0.8*cos(pi*x)*sin(pi*(y+1)/2)'
-new z 50 40 '0.8*cos(pi*(y+1)/2)'
-subplot 2 2 3:title 'parametric form':rotate 50 60:box:surf x y z 'BbwrR'
-
Function surf3 is one of most suitable (for my opinion) functions to visualize 3D data. It draw the isosurface(s) – surface(s) of constant amplitude (3D analogue of contour lines). You can draw wired isosurfaces if specify ‘#’ style.
-
-
MGL code:
-
call 'prepare3d'
-light on:alpha on
-subplot 2 2 0:title 'Surf3 plot (default)'
-rotate 50 60:box:surf3 c
-subplot 2 2 1:title '"\#" style'
-rotate 50 60:box:surf3 c '#'
-subplot 2 2 2:title '"." style'
-rotate 50 60:box:surf3 c '.'
-
call 'prepare1d'
-subplot 1 3 0 '':box:plot y(:,0)
-text y 'This is very very long string drawn along a curve' 'k'
-text y 'Another string drawn under a curve' 'Tr'
-subplot 1 3 1 '':box:plot y(:,0)
-text y 'This is very very long string drawn along a curve' 'k:C'
-text y 'Another string drawn under a curve' 'Tr:C'
-subplot 1 3 2 '':box:plot y(:,0)
-text y 'This is very very long string drawn along a curve' 'k:R'
-text y 'Another string drawn under a curve' 'Tr:R'
-
-
C++ code:
-
void smgl_text2(mglGraph *gr) // text drawing
-{
- mglData y; mgls_prepare1d(&y);
- if(big!=3) gr->SubPlot(1,3,0,"");
- gr->Box(); gr->Plot(y.SubData(-1,0));
- gr->Text(y,"This is very very long string drawn along a curve","k");
- gr->Text(y,"Another string drawn under a curve","Tr");
- if(big==3) return;
-
- gr->SubPlot(1,3,1,"");
- gr->Box(); gr->Plot(y.SubData(-1,0));
- gr->Text(y,"This is very very long string drawn along a curve","k:C");
- gr->Text(y,"Another string drawn under a curve","Tr:C");
-
- gr->SubPlot(1,3,2,"");
- gr->Box(); gr->Plot(y.SubData(-1,0));
- gr->Text(y,"This is very very long string drawn along a curve","k:R");
- gr->Text(y,"Another string drawn under a curve","Tr:R");
-}
-
Example of use triangulate for arbitrary placed points.
-
-
MGL code:
-
new x 100 '2*rnd-1':new y 100 '2*rnd-1':copy z x^2-y^2
-new g 30 30:triangulate d x y
-title 'Triangulation'
-rotate 50 60:box:light on
-triplot d x y z:triplot d x y z '#k'
-datagrid g x y z:mesh g 'm'
-
Functions triplot and quadplot draw set of triangles (or quadrangles, correspondingly) for irregular data arrays. Note, that you have to provide not only vertexes, but also the indexes of triangles or quadrangles. I.e. perform triangulation by some other library. See also triangulate.
-
Function vect is most standard way to visualize vector fields – it draw a lot of arrows or hachures for each data cell. It have a lot of options which can be seen on the figure (and in the sample code), and use color scheme for coloring (see Color scheme).
-
-
MGL code:
-
call 'prepare2v'
-call 'prepare3v'
-subplot 3 2 0 '':title 'Vect plot (default)':box:vect a b
-subplot 3 2 1 '':title '"." style; "=" style':box:vect a b '.='
-subplot 3 2 2 '':title '"f" style':box:vect a b 'f'
-subplot 3 2 3 '':title '">" style':box:vect a b '>'
-subplot 3 2 4 '':title '"<" style':box:vect a b '<'
-subplot 3 2 5:title '3d variant':rotate 50 60:box:vect ex ey ez
-
Function vect3 draw ordinary vector field plot but at slices of 3D data.
-
-
MGL code:
-
call 'prepare3v'
-subplot 2 1 0:title 'Vect3 sample':rotate 50 60
-origin 0 0 0:box:axis '_xyz'
-vect3 ex ey ez 'x':vect3 ex ey ez:vect3 ex ey ez 'z'
-subplot 2 1 1:title '"f" style':rotate 50 60
-origin 0 0 0:box:axis '_xyz'
-vect3 ex ey ez 'fx':vect3 ex ey ez 'f':vect3 ex ey ez 'fz'
-grid3 ex 'Wx':grid3 ex 'W':grid3 ex 'Wz'
-
list x -0.3 0 0.3:list y 0.3 -0.3 0.3:list e 0.7 0.7 0.7
-subplot 1 1 0:title 'Venn-like diagram'
-transptype 1:alpha on:error x y e e '!rgb@#o';alpha 0.1
-
This appendix contain the full list of symbols (characters) used by MathGL for setting up plot. Also it contain sections for full list of hot-keys supported by mglview tool and by UDAV program.
-
Create new window with empty script. Note, all scripts share variables. So, second window can be used to see some additional information of existed variables.
-
Ctrl-O
Open and execute/show script or data from file. You may switch off automatic exection in UDAV properties
-
Ctrl-S
Save script to a file.
-
Ctrl-P
Open printer dialog and print graphics.
-
Ctrl-Z
Undo changes in script editor.
-
Ctrl-Shift-Z
Redo changes in script editor.
-
Ctrl-X
Cut selected text into clipboard.
-
Ctrl-C
Copy selected text into clipboard.
-
Ctrl-V
Paste selected text from clipboard.
-
Ctrl-A
Select all text in editor.
-
Ctrl-F
Show dialog for text finding.
-
F3
Find next occurrence of the text.
-
Win-C or Meta-C
Show dialog for new command and put it into the script.
-
Win-F or Meta-F
Insert last fitted formula with found coefficients.
-
Win-S or Meta-S
Show dialog for styles and put it into the script. Styles define the plot view (color scheme, marks, dashing and so on).
-
Win-O or Meta-O
Show dialog for options and put it into the script. Options are used for additional setup the plot.
-
Win-N or Meta-N
Replace selected expression by its numerical value.
-
Win-P or Meta-P
Select file and insert its file name into the script.
-
Win-G or Meta-G
Show dialog for plot setup and put resulting code into the script. This dialog setup axis, labels, lighting and other general things.
-
Ctrl-Shift-O
Load data from file. Data will be deleted only at exit but UDAV will not ask to save it.
-
Ctrl-Shift-S
Save data to a file.
-
Ctrl-Shift-C
Copy range of numbers to clipboard.
-
Ctrl-Shift-V
Paste range of numbers from clipboard.
-
Ctrl-Shift-N
Recreate the data with new sizes and fill it by zeros.
-
Ctrl-Shift-R
Resize (interpolate) the data to specified sizes.
-
Ctrl-Shift-T
Transform data along dimension(s).
-
Ctrl-Shift-M
Make another data.
-
Ctrl-Shift-H
Find histogram of data.
-
Ctrl-T
Switch on/off transparency for the graphics.
-
Ctrl-L
Switch on/off additional lightning for the graphics.
-
Ctrl-G
Switch on/off grid of absolute coordinates.
-
Ctrl-Space
Restore default graphics rotation, zoom and perspective.
-
F5
Execute script and redraw graphics.
-
F6
Change canvas size to fill whole region.
-
F7
Stop script execution and drawing.
-
F8
Show/hide tool window with list of hidden plots.
-
F9
Restore status for ’once’ command and reload data.
-
Ctrl-F5
Run slideshow. If no parameter specified then the dialog with slideshow options will appear.
-
Ctrl-Comma, Ctrl-Period
Show next/previous slide. If no parameter specified then the dialog with slideshow options will appear.
-
Ctrl-W
Open dialog with slideshow options.
-
Ctrl-Shift-G
Copy graphics to clipboard.
-
F1
Show help on MGL commands
-
F2
Show/hide tool window with messages and information.
-
F4
Show/hide calculator which evaluate and help to type textual formulas. Textual formulas may contain data variables too.
Starting from v.1.6 the MathGL library uses new font files. The font is defined in 4 files with suffixes ‘*.vfm’, ‘*_b.vfm’, ‘*_i.vfm’, ‘*_bi.vfm’. These files are text files containing the data for roman font, bold font, italic font and bold italic font. The files (or some symbols in the files) for bold, italic or bold italic fonts can be absent. In this case the roman glyph will be used for them. By analogy, if the bold italic font is absent but the bold font is present then bold glyph will be used for bold italic. You may create these font files by yourself from *.ttf, *.otf files with the help of program font_tools. This program can be found at MathGL home site.
-
-
The format of font files (*.vfm – vector font for MathGL) is the following.
-
-
First string contains human readable comment and is always ignored.
-
Second string contains 3 numbers, delimited by space or tabulation. The order of numbers is the following: numg – the number of glyphs in the file (integer), fact – the factor for glyph sizing (mreal), size – the size of buffer for glyph description (integer).
-
After it numg-th strings with glyphs description are placed. Each string contains 6 positive numbers, delimited by space of tabulation. The order of numbers is the following: Unicode glyph ID, glyph width, number of lines in glyph, position of lines coordinates in the buffer (length is 2*number of lines), number of triangles in glyph, position of triangles coordinates in the buffer (length is 6*number of triangles).
-
The end of file contains the buffer with point coordinates at lines or triangles vertexes. The size of buffer (the number of integer) is size.
-
-
-
Each font file can be compressed by gzip.
-
-
Note: the closing contour line is done automatically (so the last segment may be absent). For starting new contour use a point with coordinates {0x3fff, 0x3fff}.
-
MGLD is textual file, which contain all required information for drawing 3D image, i.e. it contain vertexes with colors and normales, primitives with all properties, textures, and glyph descriptions. MGLD file can be imported or viewed separately, without parsing data files itself.
-
which contain signature ‘MGLD’ and number of points npnts, number of primitives nprim, number of textures ntxtr, number of glyph descriptions nglfs, and optional description. Empty strings and string with ‘#’ are ignored.
-
-
Next, file contain npnts strings with points coordinates and colors. The format of each string is
-
x y z c t ta u v w r g b a
-
Here x, y, z are coordinates, c, t are color indexes in texture, ta is normalized t according to current alpha setting, u, v, w are coordinates of normal vector (can be NAN if disabled), r, g, b, a are RGBA color values.
-
-
Next, file contain nprim strings with properties of primitives. The format of each string is
-
type n1 n2 n3 n4 id s w p
-
Here type is kind of primitive (0 - mark, 1 - line, 2 - triangle, 3 - quadrangle, 4 - glyph), n1...n4 is index of point for vertexes, id is primitive identification number, s and w are size and width if applicable, p is scaling factor for glyphs.
-
-
Next, file contain ntxtr strings with descriptions of textures. The format of each string is
-
smooth alpha colors
-
Here smooth set to enable smoothing between colors, alpha set to use half-transparent texture, colors contain color scheme itself as it described in Color scheme.
-
-
Finally, file contain nglfs entries with description of each glyph used in the figure. The format of entries are
-
nT nL
-xA yA xB yB xC yC ...
-xP yP ...
-
Here nT is the number of triangles; nL is the number of line vertexes; xA, yA, xB, yB, xC, yC are coordinates of triangles; and xP, yP, xQ, yQ are coordinates of lines. Line coordinate xP=0x3fff, yP=0x3fff denote line breaking.
-
MathGL can save points and primitives of 3D object. It contain a set of variables listed below.
-
-
-
‘width’
-
width of the image;
-
-
‘height’
-
height of the image
-
-
‘depth’
-
depth of the image, usually =sqrt(width*height);
-
-
-
‘npnts’
-
number of points (vertexes);
-
-
‘pnts’
-
array of coordinates of points (vertexes), each element is array in form [x, y, z];
-
-
-
‘nprim’
-
number of primitives;
-
-
‘prim’
-
array of primitives, each element is array in form [type, n1, n2, n3, n4, id, s, w, p, z, color].
-
-
Here type is kind of primitive (0 - mark, 1 - line, 2 - triangle, 3 - quadrangle, 4 - glyph), n1...n4 is index of point for vertexes and n2 can be index of glyph coordinate, s and w are size and width if applicable, z is average z-coordinate, id is primitive identification number, p is scaling factor for glyphs.
-
-
-
‘ncoor’
-
number of glyph positions
-
-
‘coor’
-
array of glyph positions, each element is array in form [dx,dy]
-
-
-
‘nglfs’
-
number of glyph descriptions
-
-
‘glfs’
-
array of glyph descriptions, each element is array in form [nL, [xP0, yP0, xP1, yP1 ...]]. Here nL is the number of line vertexes; and xP, yP, xQ, yQ are coordinates of lines. Line coordinate xP=0x3fff, yP=0x3fff denote line breaking.
-
MathGL can read IFS fractal parameters (see ifsfile) from a IFS file. Let remind IFS file format. File may contain several records. Each record contain the name of fractal (‘binary’ in the example below) and the body of fractal, which is enclosed in curly braces {}. Symbol ‘;’ start the comment. If the name of fractal contain ‘(3D)’ or ‘(3d)’ then the 3d IFS fractal is specified. The sample below contain two fractals: ‘binary’ – usual 2d fractal, and ‘3dfern (3D)’ – 3d fractal.
-
The full list of TeX-like commands recognizable by MathGL is shown below. If command is not recognized then it will be printed as is by ommitting ‘\’ symbol. For example, ‘\#’ produce “#”, ‘\\’ produce “\”, ‘\qq’ produce “qq”.
-
The purpose of this License is to make a manual, textbook, or other
-functional and useful document free in the sense of freedom: to
-assure everyone the effective freedom to copy and redistribute it,
-with or without modifying it, either commercially or noncommercially.
-Secondarily, this License preserves for the author and publisher a way
-to get credit for their work, while not being considered responsible
-for modifications made by others.
-
-
This License is a kind of “copyleft”, which means that derivative
-works of the document must themselves be free in the same sense. It
-complements the GNU General Public License, which is a copyleft
-license designed for free software.
-
-
We have designed this License in order to use it for manuals for free
-software, because free software needs free documentation: a free
-program should come with manuals providing the same freedoms that the
-software does. But this License is not limited to software manuals;
-it can be used for any textual work, regardless of subject matter or
-whether it is published as a printed book. We recommend this License
-principally for works whose purpose is instruction or reference.
-
-
APPLICABILITY AND DEFINITIONS
-
-
This License applies to any manual or other work, in any medium, that
-contains a notice placed by the copyright holder saying it can be
-distributed under the terms of this License. Such a notice grants a
-world-wide, royalty-free license, unlimited in duration, to use that
-work under the conditions stated herein. The “Document”, below,
-refers to any such manual or work. Any member of the public is a
-licensee, and is addressed as “you”. You accept the license if you
-copy, modify or distribute the work in a way requiring permission
-under copyright law.
-
-
A “Modified Version” of the Document means any work containing the
-Document or a portion of it, either copied verbatim, or with
-modifications and/or translated into another language.
-
-
A “Secondary Section” is a named appendix or a front-matter section
-of the Document that deals exclusively with the relationship of the
-publishers or authors of the Document to the Document’s overall
-subject (or to related matters) and contains nothing that could fall
-directly within that overall subject. (Thus, if the Document is in
-part a textbook of mathematics, a Secondary Section may not explain
-any mathematics.) The relationship could be a matter of historical
-connection with the subject or with related matters, or of legal,
-commercial, philosophical, ethical or political position regarding
-them.
-
-
The “Invariant Sections” are certain Secondary Sections whose titles
-are designated, as being those of Invariant Sections, in the notice
-that says that the Document is released under this License. If a
-section does not fit the above definition of Secondary then it is not
-allowed to be designated as Invariant. The Document may contain zero
-Invariant Sections. If the Document does not identify any Invariant
-Sections then there are none.
-
-
The “Cover Texts” are certain short passages of text that are listed,
-as Front-Cover Texts or Back-Cover Texts, in the notice that says that
-the Document is released under this License. A Front-Cover Text may
-be at most 5 words, and a Back-Cover Text may be at most 25 words.
-
-
A “Transparent” copy of the Document means a machine-readable copy,
-represented in a format whose specification is available to the
-general public, that is suitable for revising the document
-straightforwardly with generic text editors or (for images composed of
-pixels) generic paint programs or (for drawings) some widely available
-drawing editor, and that is suitable for input to text formatters or
-for automatic translation to a variety of formats suitable for input
-to text formatters. A copy made in an otherwise Transparent file
-format whose markup, or absence of markup, has been arranged to thwart
-or discourage subsequent modification by readers is not Transparent.
-An image format is not Transparent if used for any substantial amount
-of text. A copy that is not “Transparent” is called “Opaque”.
-
-
Examples of suitable formats for Transparent copies include plain
-ASCII without markup, Texinfo input format, LaTeX input
-format, SGML or XML using a publicly available
-DTD, and standard-conforming simple HTML,
-PostScript or PDF designed for human modification. Examples
-of transparent image formats include PNG, XCF and
-JPG. Opaque formats include proprietary formats that can be
-read and edited only by proprietary word processors, SGML or
-XML for which the DTD and/or processing tools are
-not generally available, and the machine-generated HTML,
-PostScript or PDF produced by some word processors for
-output purposes only.
-
-
The “Title Page” means, for a printed book, the title page itself,
-plus such following pages as are needed to hold, legibly, the material
-this License requires to appear in the title page. For works in
-formats which do not have any title page as such, “Title Page” means
-the text near the most prominent appearance of the work’s title,
-preceding the beginning of the body of the text.
-
-
A section “Entitled XYZ” means a named subunit of the Document whose
-title either is precisely XYZ or contains XYZ in parentheses following
-text that translates XYZ in another language. (Here XYZ stands for a
-specific section name mentioned below, such as “Acknowledgements”,
-“Dedications”, “Endorsements”, or “History”.) To “Preserve the Title”
-of such a section when you modify the Document means that it remains a
-section “Entitled XYZ” according to this definition.
-
-
The Document may include Warranty Disclaimers next to the notice which
-states that this License applies to the Document. These Warranty
-Disclaimers are considered to be included by reference in this
-License, but only as regards disclaiming warranties: any other
-implication that these Warranty Disclaimers may have is void and has
-no effect on the meaning of this License.
-
-
VERBATIM COPYING
-
-
You may copy and distribute the Document in any medium, either
-commercially or noncommercially, provided that this License, the
-copyright notices, and the license notice saying this License applies
-to the Document are reproduced in all copies, and that you add no other
-conditions whatsoever to those of this License. You may not use
-technical measures to obstruct or control the reading or further
-copying of the copies you make or distribute. However, you may accept
-compensation in exchange for copies. If you distribute a large enough
-number of copies you must also follow the conditions in section 3.
-
-
You may also lend copies, under the same conditions stated above, and
-you may publicly display copies.
-
-
COPYING IN QUANTITY
-
-
If you publish printed copies (or copies in media that commonly have
-printed covers) of the Document, numbering more than 100, and the
-Document’s license notice requires Cover Texts, you must enclose the
-copies in covers that carry, clearly and legibly, all these Cover
-Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on
-the back cover. Both covers must also clearly and legibly identify
-you as the publisher of these copies. The front cover must present
-the full title with all words of the title equally prominent and
-visible. You may add other material on the covers in addition.
-Copying with changes limited to the covers, as long as they preserve
-the title of the Document and satisfy these conditions, can be treated
-as verbatim copying in other respects.
-
-
If the required texts for either cover are too voluminous to fit
-legibly, you should put the first ones listed (as many as fit
-reasonably) on the actual cover, and continue the rest onto adjacent
-pages.
-
-
If you publish or distribute Opaque copies of the Document numbering
-more than 100, you must either include a machine-readable Transparent
-copy along with each Opaque copy, or state in or with each Opaque copy
-a computer-network location from which the general network-using
-public has access to download using public-standard network protocols
-a complete Transparent copy of the Document, free of added material.
-If you use the latter option, you must take reasonably prudent steps,
-when you begin distribution of Opaque copies in quantity, to ensure
-that this Transparent copy will remain thus accessible at the stated
-location until at least one year after the last time you distribute an
-Opaque copy (directly or through your agents or retailers) of that
-edition to the public.
-
-
It is requested, but not required, that you contact the authors of the
-Document well before redistributing any large number of copies, to give
-them a chance to provide you with an updated version of the Document.
-
-
MODIFICATIONS
-
-
You may copy and distribute a Modified Version of the Document under
-the conditions of sections 2 and 3 above, provided that you release
-the Modified Version under precisely this License, with the Modified
-Version filling the role of the Document, thus licensing distribution
-and modification of the Modified Version to whoever possesses a copy
-of it. In addition, you must do these things in the Modified Version:
-
-
-
Use in the Title Page (and on the covers, if any) a title distinct
-from that of the Document, and from those of previous versions
-(which should, if there were any, be listed in the History section
-of the Document). You may use the same title as a previous version
-if the original publisher of that version gives permission.
-
-
List on the Title Page, as authors, one or more persons or entities
-responsible for authorship of the modifications in the Modified
-Version, together with at least five of the principal authors of the
-Document (all of its principal authors, if it has fewer than five),
-unless they release you from this requirement.
-
-
State on the Title page the name of the publisher of the
-Modified Version, as the publisher.
-
-
Preserve all the copyright notices of the Document.
-
-
Add an appropriate copyright notice for your modifications
-adjacent to the other copyright notices.
-
-
Include, immediately after the copyright notices, a license notice
-giving the public permission to use the Modified Version under the
-terms of this License, in the form shown in the Addendum below.
-
-
Preserve in that license notice the full lists of Invariant Sections
-and required Cover Texts given in the Document’s license notice.
-
-
Include an unaltered copy of this License.
-
-
Preserve the section Entitled “History”, Preserve its Title, and add
-to it an item stating at least the title, year, new authors, and
-publisher of the Modified Version as given on the Title Page. If
-there is no section Entitled “History” in the Document, create one
-stating the title, year, authors, and publisher of the Document as
-given on its Title Page, then add an item describing the Modified
-Version as stated in the previous sentence.
-
-
Preserve the network location, if any, given in the Document for
-public access to a Transparent copy of the Document, and likewise
-the network locations given in the Document for previous versions
-it was based on. These may be placed in the “History” section.
-You may omit a network location for a work that was published at
-least four years before the Document itself, or if the original
-publisher of the version it refers to gives permission.
-
-
For any section Entitled “Acknowledgements” or “Dedications”, Preserve
-the Title of the section, and preserve in the section all the
-substance and tone of each of the contributor acknowledgements and/or
-dedications given therein.
-
-
Preserve all the Invariant Sections of the Document,
-unaltered in their text and in their titles. Section numbers
-or the equivalent are not considered part of the section titles.
-
-
Delete any section Entitled “Endorsements”. Such a section
-may not be included in the Modified Version.
-
-
Do not retitle any existing section to be Entitled “Endorsements” or
-to conflict in title with any Invariant Section.
-
-
Preserve any Warranty Disclaimers.
-
-
-
If the Modified Version includes new front-matter sections or
-appendices that qualify as Secondary Sections and contain no material
-copied from the Document, you may at your option designate some or all
-of these sections as invariant. To do this, add their titles to the
-list of Invariant Sections in the Modified Version’s license notice.
-These titles must be distinct from any other section titles.
-
-
You may add a section Entitled “Endorsements”, provided it contains
-nothing but endorsements of your Modified Version by various
-parties—for example, statements of peer review or that the text has
-been approved by an organization as the authoritative definition of a
-standard.
-
-
You may add a passage of up to five words as a Front-Cover Text, and a
-passage of up to 25 words as a Back-Cover Text, to the end of the list
-of Cover Texts in the Modified Version. Only one passage of
-Front-Cover Text and one of Back-Cover Text may be added by (or
-through arrangements made by) any one entity. If the Document already
-includes a cover text for the same cover, previously added by you or
-by arrangement made by the same entity you are acting on behalf of,
-you may not add another; but you may replace the old one, on explicit
-permission from the previous publisher that added the old one.
-
-
The author(s) and publisher(s) of the Document do not by this License
-give permission to use their names for publicity for or to assert or
-imply endorsement of any Modified Version.
-
-
COMBINING DOCUMENTS
-
-
You may combine the Document with other documents released under this
-License, under the terms defined in section 4 above for modified
-versions, provided that you include in the combination all of the
-Invariant Sections of all of the original documents, unmodified, and
-list them all as Invariant Sections of your combined work in its
-license notice, and that you preserve all their Warranty Disclaimers.
-
-
The combined work need only contain one copy of this License, and
-multiple identical Invariant Sections may be replaced with a single
-copy. If there are multiple Invariant Sections with the same name but
-different contents, make the title of each such section unique by
-adding at the end of it, in parentheses, the name of the original
-author or publisher of that section if known, or else a unique number.
-Make the same adjustment to the section titles in the list of
-Invariant Sections in the license notice of the combined work.
-
-
In the combination, you must combine any sections Entitled “History”
-in the various original documents, forming one section Entitled
-“History”; likewise combine any sections Entitled “Acknowledgements”,
-and any sections Entitled “Dedications”. You must delete all
-sections Entitled “Endorsements.”
-
-
COLLECTIONS OF DOCUMENTS
-
-
You may make a collection consisting of the Document and other documents
-released under this License, and replace the individual copies of this
-License in the various documents with a single copy that is included in
-the collection, provided that you follow the rules of this License for
-verbatim copying of each of the documents in all other respects.
-
-
You may extract a single document from such a collection, and distribute
-it individually under this License, provided you insert a copy of this
-License into the extracted document, and follow this License in all
-other respects regarding verbatim copying of that document.
-
-
AGGREGATION WITH INDEPENDENT WORKS
-
-
A compilation of the Document or its derivatives with other separate
-and independent documents or works, in or on a volume of a storage or
-distribution medium, is called an “aggregate” if the copyright
-resulting from the compilation is not used to limit the legal rights
-of the compilation’s users beyond what the individual works permit.
-When the Document is included in an aggregate, this License does not
-apply to the other works in the aggregate which are not themselves
-derivative works of the Document.
-
-
If the Cover Text requirement of section 3 is applicable to these
-copies of the Document, then if the Document is less than one half of
-the entire aggregate, the Document’s Cover Texts may be placed on
-covers that bracket the Document within the aggregate, or the
-electronic equivalent of covers if the Document is in electronic form.
-Otherwise they must appear on printed covers that bracket the whole
-aggregate.
-
-
TRANSLATION
-
-
Translation is considered a kind of modification, so you may
-distribute translations of the Document under the terms of section 4.
-Replacing Invariant Sections with translations requires special
-permission from their copyright holders, but you may include
-translations of some or all Invariant Sections in addition to the
-original versions of these Invariant Sections. You may include a
-translation of this License, and all the license notices in the
-Document, and any Warranty Disclaimers, provided that you also include
-the original English version of this License and the original versions
-of those notices and disclaimers. In case of a disagreement between
-the translation and the original version of this License or a notice
-or disclaimer, the original version will prevail.
-
-
If a section in the Document is Entitled “Acknowledgements”,
-“Dedications”, or “History”, the requirement (section 4) to Preserve
-its Title (section 1) will typically require changing the actual
-title.
-
-
TERMINATION
-
-
You may not copy, modify, sublicense, or distribute the Document except
-as expressly provided for under this License. Any other attempt to
-copy, modify, sublicense or distribute the Document is void, and will
-automatically terminate your rights under this License. However,
-parties who have received copies, or rights, from you under this
-License will not have their licenses terminated so long as such
-parties remain in full compliance.
-
-
FUTURE REVISIONS OF THIS LICENSE
-
-
The Free Software Foundation may publish new, revised versions
-of the GNU Free Documentation License from time to time. Such new
-versions will be similar in spirit to the present version, but may
-differ in detail to address new problems or concerns. See
-http://www.gnu.org/copyleft/.
-
-
Each version of the License is given a distinguishing version number.
-If the Document specifies that a particular numbered version of this
-License “or any later version” applies to it, you have the option of
-following the terms and conditions either of that specified version or
-of any later version that has been published (not as a draft) by the
-Free Software Foundation. If the Document does not specify a version
-number of this License, you may choose any version ever published (not
-as a draft) by the Free Software Foundation.
-
-
-
-
ADDENDUM: How to use this License for your documents
-
-
To use this License in a document you have written, include a copy of
-the License in the document and put the following copyright and
-license notices just after the title page:
-
-
-
Copyright (C) yearyour name.
- Permission is granted to copy, distribute and/or modify this document
- under the terms of the GNU Free Documentation License, Version 1.2
- or any later version published by the Free Software Foundation;
- with no Invariant Sections, no Front-Cover Texts, and no Back-Cover
- Texts. A copy of the license is included in the section entitled ``GNU
- Free Documentation License''.
-
-
-
If you have Invariant Sections, Front-Cover Texts and Back-Cover Texts,
-replace the “with…Texts.” line with this:
-
-
-
with the Invariant Sections being list their titles, with
- the Front-Cover Texts being list, and with the Back-Cover Texts
- being list.
-
-
-
If you have Invariant Sections without Cover Texts, or some other
-combination of the three, merge those two alternatives to suit the
-situation.
-
-
If your document contains nontrivial examples of program code, we
-recommend releasing these examples in parallel under your choice of
-free software license, such as the GNU General Public License,
-to permit their use in free software.
-
This file documents the MGL script language. It corresponds to release 2.4.2 of the MathGL library. Please report any errors in this manual to mathgl.abalakin@gmail.org. More information about MGL and MathGL can be found at the project homepage, http://mathgl.sourceforge.net/.
-
Permission is granted to copy, distribute and/or modify this document
-under the terms of the GNU Free Documentation License, Version 1.2
-or any later version published by the Free Software Foundation;
-with no Invariant Sections, no Front-Cover Texts, and no Back-Cover
-Texts. A copy of the license is included in the section entitled “GNU
-Free Documentation License.”
-
MathGL library supports the simplest scripts for data handling and plotting. These scripts can be used independently (with the help of UDAV, mglconv, mglview programs and others
-
MGL script language is rather simple. Each string is a command. First word of string is the name of command. Other words are command arguments. Words are separated from each other by space or tabulation symbol. The upper or lower case of words is important, i.e. variables a and A are different variables. Symbol `#` starts the comment (all characters after # will be ignored). The exception is situation when `#` is a part of some string. Also options can be specified after symbol `;` (see Command options). Symbol `:` starts new command (like new line character) if it is not placed inside a string or inside brackets.
-
-
If string contain references to external parameters (substrings `$0`, `$1` ... `$9`) or definitions (substrings `$a`, `$b` ... `$z`) then before execution the values of parameter/definition will be substituted instead of reference. It allows to use the same MGL script for different parameters (filenames, paths, condition and so on).
-
-
Argument can be a string, a variable (data arrays) or a number (scalars).
-
-
The string is any symbols between ordinary marks `'`. Long strings can be concatenated from several lines by `\` symbol. I.e. the string `'a +\<br> b'` will give string `'a + b'` (here `<br>` is newline). There are several operations which can be performed with string:
-
-
Concatenation of strings and numbers using `,` with out spaces (for example, `'max(u)=',u.max,' a.u.'` or `'u=',!(1+i2)` for complex numbers);
-
Getting n-th symbol of the string using `[]` (for example, `'abc'[1]` will give 'b');
-
Adding value to the last character of the string using `+` (for example, `'abc'+3` will give 'abf').
-
-
-
Usually variable have a name which is arbitrary combination of symbols (except spaces and `'`) started from a letter. Note, you can start an expression with `!` symbol if you want to use complex values. For example, the code new x 100 'x':copy !b !exp(1i*x) will create real valued data x and complex data b, which is equal to exp(I*x), where I^2=-1. A temporary array can be used as variable too:
-
-
sub-arrays (like in subdata command) as command argument. For example, a(1) or a(1,:) or a(1,:,:) is second row, a(:,2) or a(:,2,:) is third column, a(:,:,0) is first slice and so on. Also you can extract a part of array from m-th to n-th element by code a(m:n,:,:) or just a(m:n).
-
-
any column combinations defined by formulas, like a('n*w^2/exp(t)') if names for data columns was specified (by idset command or in the file at string started with ##).
-
-
any expression (without spaces) of existed variables produce temporary variable. For example, `sqrt(dat(:,5)+1)` will produce temporary variable with data values equal to tmp[i,j] = sqrt(dat[i,5,j]+1). At this symbol ``` will return transposed data array: both ``sqrt(dat(:,5)+1)` and `sqrt(`dat(:,5)+1)` will produce temporary variable with data values equal to tmp[i,j] = sqrt(dat[j,5,i]+1).
-
-
temporary variable of higher dimensions by help of []. For example, `[1,2,3]` will produce a temporary vector of 3 elements {1, 2, 3}; `[[11,12],[21,22]]` will produce matrix 2*2 and so on. Here you can join even an arrays of the same dimensions by construction like `[v1,v2,...,vn]`.
-
-
result of code for making new data (see Make another data) inside {}. For example, `{sum dat 'x'}` produce temporary variable which contain result of summation of dat along direction `x`. This is the same array tmp as produced by command `sum tmp dat 'x'`. You can use nested constructions, like `{sum {max dat 'z'} 'x'}`.
-
-
Temporary variables can not be used as 1st argument for commands which create (return) the data (like `new`, `read`, `hist` and so on).
-
-
Special names nan=#QNAN, inf=INFINITY, rnd=random value, pi=3.1415926..., on=1, off=0, all=-1, :=-1, variables with suffixes (see Data information), names defined by define command, time values (in format "hh-mm-ss_DD.MM.YYYY", "hh-mm-ss" or "DD.MM.YYYY") are treated as number. Also results of formulas with sizes 1x1x1 are treated as number (for example, `pi/dat.nx`).
-
Command may have several set of possible arguments (for example, plot ydat and plot xdat ydat). All command arguments for a selected set must be specified. However, some arguments can have default values. These argument are printed in [], like text ydat ['stl'=''] or text x y 'txt' ['fnt'='' size=-1]. At this, the record [arg1 arg2 arg3 ...] means [arg1 [arg2 [arg3 ...]]], i.e. you can omit only tailing arguments if you agree with its default values. For example, text x y 'txt' '' 1 or text x y 'txt' '' is correct, but text x y 'txt' 1 is incorrect (argument 'fnt' is missed).
-
-
You can provide several variants of arguments for a command by using `?` symbol for separating them. The actual argument being used is set by variant. At this, the last argument is used if the value of variant is large than the number of provided variants. By default the first argument is used (i.e. as for variant 0). For example, the first plot will be drawn by blue (default is the first argument `b`), but the plot after variant 1 will be drawn by red dash (the second is `r|`):
-
Below I show commands to control program flow, like, conditions, loops, define script arguments and so on. Other commands can be found in chapters MathGL core and Data processing. Note, that some of program flow commands (like define, ask, call, for, func) should be placed alone in the string.
-
-
-
-
MGL command: chdir'path'
-
Changes the current directory to path.
-
-
-
-
-
MGL command: ask$N 'question'
-
Sets N-th script argument to answer which give the user on the question. Usually this show dialog with question where user can enter some text as answer. Here N is digit (0...9) or alpha (a...z).
-
-
-
-
-
MGL command: define$N smth
-
Sets N-th script argument to smth. Note, that smth is used as is (with `'` symbols if present). Here N is digit (0...9) or alpha (a...z).
-
-
-
MGL command: definename smth
-
Create scalar variable name which have the numeric value of smth. Later you can use this variable as usual number.
-
-
-
-
MGL command: defchr$N smth
-
Sets N-th script argument to character with value evaluated from smth. Here N is digit (0...9) or alpha (a...z).
-
-
-
-
MGL command: defnum$N smth
-
Sets N-th script argument to number with value evaluated from smth. Here N is digit (0...9) or alpha (a...z).
-
-
-
-
-
-
MGL command: call'funcname' [ARG1 ARG2 ... ARG9]
-
Executes function fname (or script if function is not found). Optional arguments will be passed to functions. See also func.
-
-
-
-
MGL command: func'funcname' [narg=0]
-
Define the function fname and number of required arguments. The arguments will be placed in script parameters $1, $2, ... $9. Note, script execution is stopped at func keyword, similarly to stop command. See also return.
-
Load additional MGL command from external module (DLL or .so), located in file filename. This module have to contain array with name mgl_cmd_extra of type mglCommand, which describe provided commands.
-
-
-
-
-
-
MGL command: ifvalthenCMD
-
Executes command CMD only if val is nonzero.
-
-
-
MGL command: ifval
-
Starts block which will be executed if val is nonzero.
-
-
-
MGL command: ifdat 'cond'
-
Starts block which will be executed if dat satisfy to cond.
-
-
-
-
MGL command: elseifval
-
Starts block which will be executed if previous if or elseif is false and val is nonzero.
-
-
-
MGL command: elseifdat 'cond'
-
Starts block which will be executed if previous if or elseif is false and dat satisfy to cond.
-
-
-
-
MGL command: else
-
Starts block which will be executed if previous if or elseif is false.
-
-
-
-
MGL command: endif
-
Finishes if/elseif/else block.
-
-
-
-
-
MGL command: for$N v1 v2 [dv=1]
-
Starts loop with $N-th argument changing from v1 to v2 with the step dv. Here N is digit (0...9) or alpha (a...z).
-
-
-
MGL command: for$N dat
-
Starts loop with $N-th argument changing for dat values. Here N is digit (0...9) or alpha (a...z).
-
-
-
-
MGL command: next
-
Finishes for loop.
-
-
-
-
-
MGL command: do
-
Starts infinite loop.
-
-
-
-
MGL command: whileval
-
Continue loop iterations if val is nonzero, or finishes loop otherwise.
-
-
-
MGL command: whiledat 'cond'
-
Continue loop iterations if dat satisfy to cond, or finishes loop otherwise.
-
-
-
-
-
MGL command: onceval
-
The code between once on and once off will be executed only once. Useful for large data manipulation in programs like UDAV.
-
-
-
-
MGL command: stop
-
Terminate execution.
-
-
-
-
-
MGL command: variantval
-
Set variant of argument(s) separated by `?` symbol to be used in further commands.
-
-
-
-
-
-
MGL command: rkstepeq1;... var1;... [dt=1]
-
Make one step for ordinary differential equation(s) {var1` = eq1, ... } with time-step dt. Here variable(s) `var1`, ... are the ones, defined in MGL script previously. The Runge-Kutta 4-th order method is used for solution.
-
There are number of special comments for MGL script, which set some global behavior (like, animation, dialog for parameters and so on). All these special comments starts with double sign ##. Let consider them.
-
-
-
`##cv1 v2 [dv=1]`
-
Sets the parameter for animation loop relative to variable $0. Here v1 and v2 are initial and final values, dv is the increment.
-
-
-
`##a val`
-
Adds the parameter val to the list of animation relative to variable $0. You can use it several times (one parameter per line) or combine it with animation loop ##c.
-
-
-
`##d $I kind|label|par1|par2|...`
-
Creates custom dialog for changing plot properties. Each line adds one widget to the dialog. Here $I is id ($0,$1...$9,$a,$b...$z), label is the label of widget, kind is the kind of the widget:
-
-
`e` for editor or input line (parameter is initial value) ,
-
`v` for spinner or counter (parameters are "ini|min|max|step|big_step"),
-
`s` for slider (parameters are "ini|min|max|step"),
-
`b` for check box (parameter is "ini"; also understand "on"=1),
-
`c` for choice (parameters are possible choices).
-
-
Now, it work in FLTK-based mgllab and mglview only.
-
There is LaTeX package mgltex (was made by Diego Sejas Viscarra) which allow one to make figures directly from MGL script located in LaTeX file.
-
-
For using this package you need to specify --shell-escape option for latex/pdflatex or manually run mglconv tool with produced MGL scripts for generation of images. Don`t forgot to run latex/pdflatex second time to insert generated images into the output document. Also you need to run pdflatex third time to update converted from EPS images if you are using vector EPS output (default).
-
-
The package may have following options: draft, final — the same as in the graphicx package; on, off — to activate/deactivate the creation of scripts and graphics; comments, nocomments — to make visible/invisible comments contained inside mglcomment environments; jpg, jpeg, png — to export graphics as JPEG/PNG images; eps, epsz — to export to uncompressed/compressed EPS format as primitives; bps, bpsz — to export to uncompressed/compressed EPS format as bitmap (doesn`t work with pdflatex); pdf — to export to 3D PDF; tex — to export to LaTeX/tikz document.
-
-
The package defines the following environments:
-
-
`mgl`
-
It writes its contents to a general script which has the same name as the LaTeX document, but its extension is .mgl. The code in this environment is compiled and the image produced is included. It takes exactly the same optional arguments as the \includegraphics command, plus an additional argument imgext, which specifies the extension to save the image.
-
-
An example of usage of `mgl` environment would be:
-
\begin{mglfunc}{prepare2d}
- new a 50 40 '0.6*sin(pi*(x+1))*sin(1.5*pi*(y+1))+0.4*cos(0.75*pi*(x+1)*(y+1))'
- new b 50 40 '0.6*cos(pi*(x+1))*cos(1.5*pi*(y+1))+0.4*cos(0.75*pi*(x+1)*(y+1))'
-\end{mglfunc}
-
-\begin{figure}[!ht]
- \centering
- \begin{mgl}[width=0.85\textwidth,height=7.5cm]
- fog 0.5
- call 'prepare2d'
- subplot 2 2 0 : title 'Surf plot (default)' : rotate 50 60 : light on : box : surf a
-
- subplot 2 2 1 : title '"\#" style; meshnum 10' : rotate 50 60 : box
- surf a '#'; meshnum 10
-
- subplot 2 2 2 : title 'Mesh plot' : rotate 50 60 : box
- mesh a
-
- new x 50 40 '0.8*sin(pi*x)*sin(pi*(y+1)/2)'
- new y 50 40 '0.8*cos(pi*x)*sin(pi*(y+1)/2)'
- new z 50 40 '0.8*cos(pi*(y+1)/2)'
- subplot 2 2 3 : title 'parametric form' : rotate 50 60 : box
- surf x y z 'BbwrR'
- \end{mgl}
-\end{figure}
-
-
-
`mgladdon`
-
It adds its contents to the general script, without producing any image.
-
-
`mglcode`
-
Is exactly the same as `mgl`, but it writes its contents verbatim to its own file, whose name is specified as a mandatory argument.
-
-
`mglscript`
-
Is exactly the same as `mglcode`, but it doesn`t produce any image, nor accepts optional arguments. It is useful, for example, to create a MGL script, which can later be post processed by another package like "listings".
-
-
`mglblock`
-
It writes its contents verbatim to a file, specified as a mandatory argument, and to the LaTeX document, and numerates each line of code.
-
-
-
`mglverbatim`
-
Exactly the same as `mglblock`, but it doesn`t write to a file. This environment doesn`t have arguments.
-
-
`mglfunc`
-
Is used to define MGL functions. It takes one mandatory argument, which is the name of the function, plus one additional argument, which specifies the number of arguments of the function. The environment needs to contain only the body of the function, since the first and last lines are appended automatically, and the resulting code is written at the end of the general script, after the stop command, which is also written automatically. The warning is produced if 2 or more function with the same name is defined.
-
-
`mglcomment`
-
Is used to contain multiline comments. This comments will be visible/invisible in the output document, depending on the use of the package options comments and nocomments (see above), or the \mglcomments and \mglnocomments commands (see bellow).
-
-
`mglsetup`
-
If many scripts with the same code are to be written, the repetitive code can be written inside this environment only once, then this code will be used automatically every time the `\mglplot` command is used (see below). It takes one optional argument, which is a name to be associated to the corresponding contents of the environment; this name can be passed to the `\mglplot` command to use the corresponding block of code automatically (see below).
-
-
-
-
The package also defines the following commands:
-
-
`\mglplot`
-
It takes one mandatory argument, which is MGL instructions separated by the symbol `:` this argument can be more than one line long. It takes the same optional arguments as the `mgl` environment, plus an additional argument setup, which indicates the name associated to a block of code inside a `mglsetup` environment. The code inside the mandatory argument will be appended to the block of code specified, and the resulting code will be written to the general script.
-
-
An example of usage of `\mglplot` command would be:
-
This command takes the same optional arguments as the `mgl` environment, and one mandatory argument, which is the name of a MGL script. This command will compile the corresponding script and include the resulting image. It is useful when you have a script outside the LaTeX document, and you want to include the image, but you don`t want to type the script again.
-
-
`\mglinclude`
-
This is like `\mglgraphics` but, instead of creating/including the corresponding image, it writes the contents of the MGL script to the LaTeX document, and numerates the lines.
-
-
`\mgldir`
-
This command can be used in the preamble of the document to specify a directory where LaTeX will save the MGL scripts and generate the corresponding images. This directory is also where `\mglgraphics` and `\mglinclude` will look for scripts.
-
-
`\mglquality`
-
Adjust the quality of the MGL graphics produced similarly to quality.
-
-
`\mgltexon, \mgltexoff`
-
Activate/deactivate the creation of MGL scripts and images. Notice these commands have local behavior in the sense that their effect is from the point they are called on.
-
-
`\mglcomment, \mglnocomment`
-
Make visible/invisible the contents of the mglcomment environments. These commands have local effect too.
-
-
`\mglTeX`
-
It just pretty prints the name of the package.
-
-
-
-
As an additional feature, when an image is not found or cannot be included, instead of issuing an error, mgltex prints a box with the word `MGL image not found` in the LaTeX document.
-
The set of MathGL features is rather rich - just the number of basic graphics types
-is larger than 50. Also there are functions for data handling, plot setup and so on. In spite of it I tried to keep a similar style in function names and in the order of arguments. Mostly it is
-used for different drawing functions.
-
-
There are six most general (base) concepts:
-
-
Any picture is created in memory first. The internal (memory) representation can be different: bitmap picture (for SetQuality(MGL_DRAW_LMEM) or quality 6) or the list of vector primitives (default). After that the user may decide what he/she want: save to file, display on the screen, run animation, do additional editing and so on. This approach assures a high portability of the program - the source code will produce exactly the same picture in any OS. Another big positive consequence is the ability to create the picture in the console program (using command line, without creating a window)!
-
Every plot settings (style of lines, font, color scheme) are specified by a string. It provides convenience for user/programmer - short string with parameters is more comprehensible than a large set of parameters. Also it provides portability - the strings are the same in any OS so that it is not necessary to think about argument types.
-
All functions have “simplified” and “advanced” forms. It is done for user`s convenience. One needs to specify only one data array in the “simplified” form in order to see the result. But one may set parametric dependence of coordinates and produce rather complex curves and surfaces in the “advanced” form. In both cases the order of function arguments is the same: first data arrays, second the string with style, and later string with options for additional plot tuning.
-
All data arrays for plotting are encapsulated in mglData(A) class. This reduces the number of errors while working with memory and provides a uniform interface for data of different types (mreal, double and so on) or for formula plotting.
-
All plots are vector plots. The MathGL library is intended for handling scientific data which have vector nature (lines, faces, matrices and so on). As a result, vector representation is used in all cases! In addition, the vector representation allows one to scale the plot easily - change the canvas size by a factor of 2, and the picture will be proportionally scaled.
-
New drawing never clears things drawn already. This, in some sense, unexpected, idea allows to create a lot of “combined” graphics. For example, to make a surface with contour lines one needs to call the function for surface plotting and the function for contour lines plotting (in any order). Thus the special functions for making this “combined” plots (as it is done in Matlab and some other plotting systems) are superfluous.
-
-
-
In addition to the general concepts I want to comment on some non-trivial or less commonly used general ideas - plot positioning, axis specification and curvilinear coordinates, styles for lines, text and color scheme.
-
Two axis representations are used in MathGL. The first one consists of normalizing coordinates of data points in axis range (see Axis settings). If SetCut() is true then the outlier points are omitted, otherwise they are projected to the bounding box (see Cutting). Also, the point will be omitted if it lies inside the box defined by SetCutBox() or if the value of formula CutOff() is nonzero for its coordinates. After that, transformation formulas defined by SetFunc() or SetCoor() are applied to the data point (see Curved coordinates). Finally, the data point is plotted by one of the functions.
-
-
The range of x, y, z-axis can be specified by SetRange() or ranges functions. Its origin is specified by origin function. At this you can you can use NAN values for selecting axis origin automatically.
-
-
There is 4-th axis c (color axis or colorbar) in addition to the usual axes x, y, z. It sets the range of values for the surface coloring. Its borders are automatically set to values of z-range during the call of ranges function. Also, one can directly set it by call SetRange('c', ...). Use colorbar function for drawing the colorbar.
-
-
The form (appearence) of tick labels is controlled by SetTicks() function (see Ticks). Function SetTuneTicks switches on/off tick enhancing by factoring out acommon multiplier (for small coordinate values, like 0.001 to 0.002, or large, like from 1000 to 2000) or common component (for narrow range, like from 0.999 to 1.000). Finally, you may use functions SetTickTempl() for setting templates for tick labels (it supports TeX symbols). Also, there is a possibility to print arbitrary text as tick labels the by help of SetTicksVal() function.
-
Base colors are defined by one of symbol `wkrgbcymhRGBCYMHWlenupqLENUPQ`.
-
The color types are: `k` - black, `r` - red, `R` - dark red, `g` - green, `G` - dark green, `b` - blue, `B` - dark blue, `c` - cyan, `C` - dark cyan, `m` - magenta, `M` - dark magenta, `y` - yellow, `Y` - dark yellow (gold), `h` - gray, `H` - dark gray, `w` - white, `W` - bright gray, `l` - green-blue, `L` - dark green-blue, `e` - green-yellow, `E` - dark green-yellow, `n` - sky-blue, `N` - dark sky-blue, `u` - blue-violet, `U` - dark blue-violet, `p` - purple, `P` - dark purple, `q` - orange, `Q` - dark orange (brown).
-
-
You can also use “bright” colors. The “bright” color contain 2 symbols in brackets `{cN}`: first one is the usual symbol for color id, the second one is a digit for its brightness. The digit can be in range `1`...`9`. Number `5` corresponds to a normal color, `1` is a very dark version of the color (practically black), and `9` is a very bright version of the color (practically white). For example, the colors can be `{b2}` `{b7}` `{r7}` and so on.
-
-
Finally, you can specify RGB or RGBA values of a color using format `{xRRGGBB}` or `{xRRGGBBAA}` correspondingly. For example, `{xFF9966}` give you
-melone color.
-
The line style is defined by the string which may contain specifications for color (`wkrgbcymhRGBCYMHWlenupqLENUPQ`), dashing style (`-|;:ji=` or space), width (`123456789`) and marks (`*o+xsd.^v<>` and `#` modifier). If one of the type of information is omitted then default values used with next color from palette (see Palette and colors). Note, that internal color counter will be nullified by any change of palette. This includes even hidden change (for example, by box or axis functions).
-By default palette contain following colors: dark gray `H`, blue `b`, green `g`, red `r`, cyan `c`, magenta `m`, yellow `y`, gray `h`, green-blue `l`, sky-blue `n`, orange `q`, green-yellow `e`, blue-violet `u`, purple `p`.
-
-
Dashing style has the following meaning: space - no line (usable for plotting only marks), `-` - solid line (■■■■■■■■■■■■■■■■), `|` - long dashed line (■■■■■■■■□□□□□□□□), `;` - dashed line (■■■■□□□□■■■■□□□□), `=` - small dashed line (■■□□■■□□■■□□■■□□), `:` - dotted line (■□□□■□□□■□□□■□□□), `j` - dash-dotted line (■■■■■■■□□□□■□□□□), `i` - small dash-dotted line (■■■□□■□□■■■□□■□□), `{dNNNN}` - manual mask style (for v.2.3 and later, like `{df090}` for (■■■■□□□□■□□■□□□□)).
You can provide user-defined symbols (see addsymbol) to draw it as marker by using `&` style. In particular, `&*`, `&o`, `&+`, `&x`, `&s`, `&d`, `&.`, `&^`, `&v`, `&<`, `&>` will draw user-defined symbol `*o+xsd.^v<>` correspondingly; and
-`&#o`, `&#+`, `&#x`, `&#s`, `&#d`, `&#.`, `&#^`, `&#v`, `&#<`, `&#>` will draw user-defined symbols `YOPXSDCTVLR` correspondingly. Note, that wired version of user-defined symbols will be drawn if you set negative marker size (see marksize or size in Command options).
-
-
One may specify to draw a special symbol (an arrow) at the beginning and at the end of line. This is done if the specification string contains one of the following symbols: `A` - outer arrow, `V` - inner arrow, `I` - transverse hatches, `K` - arrow with hatches, `T` - triangle, `S` - square, `D` - rhombus, `O` - circle, `X` - skew cross, `_` - nothing (the default). The following rule applies: the first symbol specifies the arrow at the end of line, the second specifies the arrow at the beginning of the line. For example, `r-A` defines a red solid line with usual arrow at the end, `b|AI` defines a blue dash line with an arrow at the end and with hatches at the beginning, `_O` defines a line with the current style and with a circle at the beginning. These styles are applicable during the graphics plotting as well (for example, 1D plotting).
-
The color scheme is used for determining the color of surfaces, isolines, isosurfaces and so on. The color scheme is defined by the string, which may contain several characters that are color id (see Line styles) or characters `#:|`. Symbol `#` switches to mesh drawing or to a wire plot. Symbol `|` disables color interpolation in color scheme, which can be useful, for example, for sharp colors during matrix plotting. Symbol `:` terminate the color scheme parsing. Following it, the user may put styles for the text, rotation axis for curves/isocontours, and so on. Color scheme may contain up to 32 color values.
-
-
The final color is a linear interpolation of color array. The color array is constructed from the string ids (including “bright” colors, see Color styles). The argument is the amplitude normalized in color range (see Axis settings). For example, string containing 4 characters `bcyr` corresponds to a colorbar from blue (lowest value) through cyan (next value) through yellow (next value) to the red (highest value). String `kw` corresponds to a colorbar from black (lowest value) to white (highest value). String `m` corresponds to a simple magenta color.
-
-
The special 2-axis color scheme (like in map plot) can be used if it contain symbol `%`. In this case the second direction (alpha channel) is used as second coordinate for colors. At this, up to 4 colors can be specified for corners: {c1,a1}, {c2,a1}, {c1,a2}, {c2,a2}. Here color and alpha ranges are {c1,c2} and {a1,a2} correspondingly. If one specify less than 4 colors then black color is used for corner {c1,a1}. If only 2 colors are specified then the color of their sum is used for corner {c2,a2}.
-
-
There are several useful combinations. String `kw` corresponds to the simplest gray color scheme where higher values are brighter. String `wk` presents the inverse gray color scheme where higher value is darker. Strings `kRryw`, `kGgw`, `kBbcw` present the well-known hot, summer and winter color schemes. Strings `BbwrR` and `bBkRr` allow to view bi-color figure on white or black background, where negative values are blue and positive values are red. String `BbcyrR` gives a color scheme similar to the well-known jet color scheme.
-
-
For more precise coloring, you can change default (equidistant) position of colors in color scheme. The format is `{CN,pos}`, `{CN,pos}` or `{xRRGGBB,pos}`. The position value pos should be in range [0, 1]. Note, that alternative method for fine tuning of the color scheme is using the formula for coloring (see Curved coordinates).
-
-
-
-
When coloring by coordinate (used in map), the final color is determined by the position of the point in 3d space and is calculated from formula c=x*c[1] + y*c[2]. Here, c[1], c[2] are the first two elements of color array; x, y are normalized to axis range coordinates of the point.
-
-
Additionally, MathGL can apply mask to face filling at bitmap rendering. The kind of mask is specified by one of symbols `-+=;oOsS~<>jdD*^` in color scheme. Mask can be rotated by arbitrary angle by command mask or by three predefined values +45, -45 and 90 degree by symbols `\/I` correspondingly. Examples of predefined masks are shown on the figure below.
-
-
-
-
However, you can redefine mask for one symbol by specifying new matrix of size 8*8 as second argument for mask command. For example, the right-down subplot on the figure above is produced by code
-mask '+' 'ff00182424f800':dens a '3+'
-or just use manual mask style (for v.2.3 and later)
-dens a '3{s00ff00182424f800}'
-
Text style is specified by the string which may contain: color id characters `wkrgbcymhRGBCYMHW` (see Color styles), and font style (`ribwou`) and/or alignment (`LRC`) specifications. At this, font style and alignment begin after the separator `:`. For example, `r:iCb` sets the bold (`b`) italic (`i`) font text aligned at the center (`C`) and with red color (`r`). Starting from MathGL v.2.3, you can set not single color for whole text, but use color gradient for printed text (see Color scheme).
-
-
The font styles are: `r` - roman (or regular) font, `i` - italic style, `b` - bold style. By default roman roman font is used. The align types are: `L` - align left (default), `C` - align center, `R` - align right, `T` - align under, `V` - align center vertical. Additional font effects are: `w` - wired, `o` - over-lined, `u` - underlined.
-
-
Also a parsing of the LaTeX-like syntax is provided. There are commands for the font style changing inside the string (for example, use \b for bold font): \a or \overline - over-lined, \b or \textbf - bold, \i or \textit - italic, \r or \textrm - roman (disable bold and italic attributes), \u or \underline - underlined, \w or \wire - wired, \big - bigger size, @ - smaller size. The lower and upper indexes are specified by `_` and `^` symbols. At this the changed font style is applied only on next symbol or symbols in braces {}. The text in braces {} are treated as single symbol that allow one to print the index of index. For example, compare the strings `sin (x^{2^3})` and `sin (x^2^3)`. You may also change text color inside string by command #? or by \color? where `?` is symbolic id of the color (see Color styles). For example, words `blue` and `red` will be colored in the string `#b{blue} and \colorr{red} text`. The most of functions understand the newline symbol `\n` and allows to print multi-line text. Finally, you can use arbitrary (if it was defined in font-face) UTF codes by command \utf0x????. For example, \utf0x3b1 will produce
- α symbol.
-
-
The most of commands for special TeX or AMSTeX symbols, the commands for font style changing (\textrm, \textbf, \textit, \textsc, \overline, \underline), accents (\hat, \tilde, \dot, \ddot, \acute, \check, \grave, \bar, \breve) and roots (\sqrt, \sqrt3, \sqrt4) are recognized. The full list contain approximately 2000 commands. Note that first space symbol after the command is ignored, but second one is printed as normal symbol (space). For example, the following strings produce the same result \tilde a: `\tilde{a}`; `\tilde a`; `\tilde{}a`.
-
-In particular, the Greek letters are recognizable special symbols: α - \alpha, β - \beta, γ - \gamma, δ - \delta, ε - \epsilon, η - \eta, ι - \iota, χ - \chi, κ - \kappa, λ - \lambda, μ - \mu, ν - \nu, o - \o, ω - \omega, ϕ - \phi, π - \pi, ψ - \psi, ρ - \rho, σ - \sigma, θ - \theta, τ - \tau, υ - \upsilon, ξ - \xi, ζ - \zeta, ς - \varsigma, ɛ - \varepsilon, ϑ - \vartheta, φ - \varphi, ϰ - \varkappa; A - \Alpha, B - \Beta, Γ - \Gamma, Δ - \Delta, E - \Epsilon, H - \Eta, I - \Iota, C - \Chi, K - \Kappa, Λ - \Lambda, M - \Mu, N - \Nu, O - \O, Ω - \Omega, Φ - \Phi, Π - \Pi, Ψ - \Psi, R - \Rho, Σ - \Sigma, Θ - \Theta, T - \Tau, Υ - \Upsilon, Ξ - \Xi, Z - \Zeta.
-
-
The font size can be defined explicitly (if size>0) or relatively to a base font size as |size|*FontSize (if size<0). The value size=0 specifies that the string will not be printed. The base font size is measured in internal “MathGL” units. Special functions SetFontSizePT(), SetFontSizeCM(), SetFontSizeIN() (see Font settings) allow one to set it in more “common” variables for a given dpi value of the picture.
-
MathGL have the fast variant of textual formula evaluation
-. There are a lot of functions and operators available. The operators are: `+` - addition, `-` - subtraction, `*` - multiplication, `/` - division, `%` - modulo, `^` - integer power. Also there are logical “operators”: `<` - true if x<y, `>` - true if x>y, `=` - true if x=y, `&` - true if x and y both nonzero, `|` - true if x or y nonzero. These logical operators have lowest priority and return 1 if true or 0 if false.
-
-
The basic functions are: `sqrt(x)` - square root of x, `pow(x,y)` - power x in y, `ln(x)` - natural logarithm of x, `lg(x)` - decimal logarithm of x, `log(a,x)` - logarithm base a of x, `abs(x)` - absolute value of x, `sign(x)` - sign of x, `mod(x,y)` - x modulo y, `step(x)` - step function, `int(x)` - integer part of x, `rnd` - random number, `random(x)` - random data of size as in x, `hypot(x,y)`=sqrt(x^2+y^2) - hypotenuse, `cmplx(x,y)`=x+i*y - complex number, `pi` - number
-π = 3.1415926…, inf=∞
-
-
Functions for complex numbers `real(x)`, `imag(x)`, `abs(x)`, `arg(x)`, `conj(x)`.
-
There are a set of special functions: `gamma(x)` - Gamma function Γ(x) = ∫0∞ tx-1 exp(-t) dt, `gamma_inc(x,y)` - incomplete Gamma function Γ(x,y) = ∫y∞ tx-1 exp(-t) dt, `psi(x)` - digamma function ψ(x) = Γ′(x)/Γ(x) for x≠0, `ai(x)` - Airy function Ai(x), `bi(x)` - Airy function Bi(x), `cl(x)` - Clausen function, `li2(x)` (or `dilog(x)`) - dilogarithm Li2(x) = -ℜ∫0xds log(1-s)/s, `sinc(x)` - compute sinc(x) = sin(πx)/(πx) for any value of x, `zeta(x)` - Riemann zeta function ζ(s) = ∑k=1∞k-s for arbitrary s≠1, `eta(x)` - eta function η(s) = (1 - 21-s)ζ(s) for arbitrary s, `lp(l,x)` - Legendre polynomial Pl(x), (|x|≤1, l≥0), `w0(x)` - principal branch of the Lambert W function, `w1(x)` - principal branch of the Lambert W function. Function W(x) is defined to be solution of the equation: W exp(W) = x.
-
-
The exponent integrals are: `ci(x)` - Cosine integral Ci(x) = ∫0xdt cos(t)/t, `si(x)` - Sine integral Si(x) = ∫0xdt sin(t)/t, `erf(x)` - error function erf(x) = (2/√π) ∫0xdt exp(-t2) , `ei(x)` - exponential integral Ei(x) = -PV(∫-x∞dt exp(-t)/t) (where PV denotes the principal value of the integral), `e1(x)` - exponential integral E1(x) = ℜ∫1∞dt exp(-xt)/t, `e2(x)` - exponential integral E2(x) = ℜ∫1∞dt exp(-xt)/t2, `ei3(x)` - exponential integral Ei3(x) = ∫0xdt exp(-t3) for x≥0.
-
-
Bessel functions are: `j(nu,x)` - regular cylindrical Bessel function of fractional order nu, `y(nu,x)` - irregular cylindrical Bessel function of fractional order nu, `i(nu,x)` - regular modified Bessel function of fractional order nu, `k(nu,x)` - irregular modified Bessel function of fractional order nu.
-
-
Elliptic integrals are: `ee(k)` - complete elliptic integral is denoted by E(k) = E(π/2,k), `ek(k)` - complete elliptic integral is denoted by K(k) = F(π/2,k), `e(phi,k)` - elliptic integral E(φ,k) = ∫0φdt √(1 - k2sin2(t)), `f(phi,k)` - elliptic integral F(φ,k) = ∫0φdt 1/√(1 - k2sin2(t))
Note, some of these functions are unavailable if MathGL was compiled without GSL support.
-
-
There is no difference between lower or upper case in formulas. If argument value lie outside the range of function definition then function returns NaN.
-
Command options allow the easy setup of the selected plot by changing global settings only for this plot. Each option start from symbol `;`. Options work so that MathGL remember the current settings, change settings as it being set in the option, execute function and return the original settings back. So, the options are most usable for plotting functions.
-
-
The most useful options are xrange, yrange, zrange. They sets the boundaries for data change. This boundaries are used for automatically filled variables. So, these options allow one to change the position of some plots. For example, in command Plot(y,"","xrange 0.1 0.9"); or plot y; xrange 0.1 0.9 the x coordinate will be equidistantly distributed in range 0.1 ... 0.9. See Using options, for sample code and picture.
-
-
The full list of options are:
-
-
-
-
MGL option: alphaval
-
Sets alpha value (transparency) of the plot. The value should be in range [0, 1]. See also alphadef.
-
-
-
-
-
MGL option: xrangeval1 val2
-
Sets boundaries of x coordinate change for the plot. See also xrange.
-
-
-
-
MGL option: yrangeval1 val2
-
Sets boundaries of y coordinate change for the plot. See also yrange.
-
-
-
-
MGL option: zrangeval1 val2
-
Sets boundaries of z coordinate change for the plot. See also zrange.
-
-
-
-
-
MGL option: cutval
-
Sets whether to cut or to project the plot points lying outside the bounding box. See also cut.
-
Adds string `txt` to internal legend accumulator. The style of described line and mark is taken from arguments of the last 1D plotting command. See also legend.
-
-
-
-
MGL option: valueval
-
Set the value to be used as additional numeric parameter in plotting command.
-
This chapter contains a lot of plotting commands for 1D, 2D and 3D data. It also encapsulates parameters for axes drawing. Moreover an arbitrary coordinate transformation can be used for each axis. Additional information about colors, fonts, formula parsing can be found in General concepts. The full list of symbols used by MathGL for setting up plots can be found in Symbols for styles.
-
-
-
Some of MathGL features will appear only in novel versions. To test used MathGL version you can use following function.
-
-
MGL command: version'ver'
-
Return zero if MathGL version is appropriate for required by ver, i.e. if major version is the same and minor version is greater or equal to one in ver.
-
Functions and variables in this group influences on overall graphics appearance. So all of them should be placed before any actual plotting function calls.
-
-
-
MGL command: reset
-
Restore initial values for all of parameters and clear the image.
-
-
-
-
MGL command: setupval flag
-
Sets the value of internal binary flag to val. The list of flags can be found at define.h. The current list of flags are:
-
#define MGL_ENABLE_CUT 0x00000004 ///< Flag which determines how points outside bounding box are drown.
-#define MGL_ENABLE_RTEXT 0x00000008 ///< Use text rotation along axis
-#define MGL_AUTO_FACTOR 0x00000010 ///< Enable autochange PlotFactor
-#define MGL_ENABLE_ALPHA 0x00000020 ///< Flag that Alpha is used
-#define MGL_ENABLE_LIGHT 0x00000040 ///< Flag of using lightning
-#define MGL_TICKS_ROTATE 0x00000080 ///< Allow ticks rotation
-#define MGL_TICKS_SKIP 0x00000100 ///< Allow ticks rotation
-#define MGL_DISABLE_SCALE 0x00000200 ///< Temporary flag for disable scaling (used for axis)
-#define MGL_FINISHED 0x00000400 ///< Flag that final picture (i.e. mglCanvas::G) is ready
-#define MGL_USE_GMTIME 0x00000800 ///< Use gmtime instead of localtime
-#define MGL_SHOW_POS 0x00001000 ///< Switch to show or not mouse click position
-#define MGL_CLF_ON_UPD 0x00002000 ///< Clear plot before Update()
-#define MGL_NOSUBTICKS 0x00004000 ///< Disable subticks drawing (for bounding box)
-#define MGL_LOCAL_LIGHT 0x00008000 ///< Keep light sources for each inplot
-#define MGL_VECT_FRAME 0x00010000 ///< Use DrwDat to remember all data of frames
-#define MGL_REDUCEACC 0x00020000 ///< Reduce accuracy of points (to reduce size of output files)
-#define MGL_PREFERVC 0x00040000 ///< Prefer vertex color instead of texture if output format supports
-#define MGL_ONESIDED 0x00080000 ///< Render only front side of surfaces if output format supports (for debugging)
-#define MGL_NO_ORIGIN 0x00100000 ///< Don't draw tick labels at axis origin
-#define MGL_GRAY_MODE 0x00200000 ///< Convert all colors to gray ones
-#define MGL_FULL_CURV 0x00400000 ///< Disable omitting points in straight-line part(s)
-#define MGL_NO_SCALE_REL 0x00800000 ///< Disable font scaling in relative inplots
-
There are several functions and variables for setup transparency. The general function is alpha which switch on/off the transparency for overall plot. It influence only for graphics which created after alpha call (with one exception, OpenGL). Function alphadef specify the default value of alpha-channel. Finally, function transptype set the kind of transparency. See Transparency and lighting, for sample code and picture.
-
-
-
MGL command: alpha[val=on]
-
Sets the transparency on/off and returns previous value of transparency. It is recommended to call this function before any plotting command. Default value is transparency off.
-
-
-
-
MGL command: alphadefval
-
Sets default value of alpha channel (transparency) for all plotting functions. Initial value is 0.5.
-
-
-
-
MGL command: transptypeval
-
Set the type of transparency. Possible values are:
-
-
Normal transparency (`0`) - below things is less visible than upper ones. It does not look well in OpenGL mode (mglGraphGL) for several surfaces.
-
Glass-like transparency (`1`) - below and upper things are commutable and just decrease intensity of light by RGB channel.
-
Lamp-like transparency (`2`) - below and upper things are commutable and are the source of some additional light. I recommend to set SetAlphaDef(0.3) or less for lamp-like transparency.
-
There are several functions for setup lighting. The general function is light which switch on/off the lighting for overall plot. It influence only for graphics which created after light call (with one exception, OpenGL). Generally MathGL support up to 10 independent light sources. But in OpenGL mode only 8 of light sources is used due to OpenGL limitations. The position, color, brightness of each light source can be set separately. By default only one light source is active. It is source number 0 with white color, located at top of the plot. See Lighting sample, for sample code and picture.
-
-
-
MGL command: light[val=on]
-
Sets the using of light on/off for overall plot. Function returns previous value of lighting. Default value is lightning off.
-
The function adds a light source with identification n in direction d with color c and with brightness bright (which must be in range [0,1]). If position r is specified and isn`t NAN then light source is supposed to be local otherwise light source is supposed to be placed at infinity.
-
-
-
-
MGL command: diffuseval
-
Set brightness of diffusive light (only for local light sources).
-
-
-
-
MGL command: ambientval
-
Sets the brightness of ambient light. The value should be in range [0,1].
-
-
-
-
MGL command: attachlightval
-
Set to attach light settings to inplot/subplot. Note, OpenGL and some output formats don`t support this feature.
-
Function imitate a fog in the plot. Fog start from relative distance dz from view point and its density growths exponentially in depth. So that the fog influence is determined by law ~ 1-exp(-d*z). Here z is normalized to 1 depth of the plot. If value d=0 then the fog is absent. Note, that fog was applied at stage of image creation, not at stage of drawing. See Adding fog, for sample code and picture.
-
These variables control the default (initial) values for most graphics parameters including sizes of markers, arrows, line width and so on. As any other settings these ones will influence only on plots created after the settings change.
-
Sets size of marks for 1D plotting. Default value is 1.
-
-
-
-
MGL command: arrowsizeval
-
Sets size of arrows for 1D plotting, lines and curves (see Primitives). Default value is 1.
-
-
-
-
MGL command: meshnumval
-
Sets approximate number of lines in mesh, fall, grid2, and also the number of hachures in vect, dew, and the number of cells in cloud, and the number of markers in plot, tens, step, mark, textmark. By default (=0) it draws all lines/hachures/cells/markers.
-
-
-
-
MGL command: facenumval
-
Sets approximate number of visible faces. Can be used for speeding up drawing by cost of lower quality. By default (=0) it draws all of them.
-
-
-
-
MGL command: plotid'id'
-
Sets default name id as filename for saving (in FLTK window for example).
-
-
-
-
-
MGL command: pendeltaval
-
Changes the blur around lines and text (default is 1). For val>1 the text and lines are more sharped. For val<1 the text and lines are more blurred.
-
These variables and functions set the condition when the points are excluded (cutted) from the drawing. Note, that a point with NAN value(s) of coordinate or amplitude will be automatically excluded from the drawing. See Cutting sample, for sample code and picture.
-
-
-
MGL command: cutval
-
Flag which determines how points outside bounding box are drawn. If it is true then points are excluded from plot (it is default) otherwise the points are projected to edges of bounding box.
-
-
-
-
MGL command: cutx1 y1 z1 x2 y2 z2
-
Lower and upper edge of the box in which never points are drawn. If both edges are the same (the variables are equal) then the cutting box is empty.
-
-
-
-
MGL command: cut'cond'
-
Sets the cutting off condition by formula cond. This condition determine will point be plotted or not. If value of formula is nonzero then point is omitted, otherwise it plotted. Set argument as "" to disable cutting off condition.
-
Font style for text and labels (see text). Initial style is `fnt`=`:rC` give Roman font with centering. Parameter val sets the size of font for tick and axis labels. Default font size of axis labels is 1.4 times large than for tick labels. For more detail, see Font styles.
-
Sets the palette as selected colors. Default value is "Hbgrcmyhlnqeup" that corresponds to colors: dark gray `H`, blue `b`, green `g`, red `r`, cyan `c`, magenta `m`, yellow `y`, gray `h`, blue-green `l`, sky-blue `n`, orange `q`, yellow-green `e`, blue-violet `u`, purple `p`. The palette is used mostly in 1D plots (see 1D plotting) for curves which styles are not specified. Internal color counter will be nullified by any change of palette. This includes even hidden change (for example, by box or axis functions).
-
Sets new bit matrix hex of size 8*8 for mask with given id. This is global setting which influence on any later usage of symbol id. The predefined masks are (see Color scheme): `-` is 000000FF00000000, `+` is 080808FF08080808, `=` is 0000FF00FF000000, `;` is 0000007700000000, `o` is 0000182424180000, `O` is 0000183C3C180000, `s` is 00003C24243C0000, `S` is 00003C3C3C3C0000, `~` is 0000060990600000, `<` is 0060584658600000, `>` is 00061A621A060000, `j` is 0000005F00000000, `d` is 0008142214080000, `D` is 00081C3E1C080000, `*` is 8142241818244281, `^` is 0000001824420000.
-
-
-
-
MGL command: maskangle
-
Sets the default rotation angle (in degrees) for masks. Note, you can use symbols `\`, `/`, `I` in color scheme for setting rotation angles as 45, -45 and 90 degrees correspondingly.
-
These large set of variables and functions control how the axis and ticks will be drawn. Note that there is 3-step transformation of data coordinates are performed. Firstly, coordinates are projected if Cut=true (see Cutting), after it transformation formulas are applied, and finally the data was normalized in bounding box. Note, that MathGL will produce warning if axis range and transformation formulas are not compatible.
-
Sets or adds the range for `x`-,`y`-,`z`- coordinate or coloring (`c`). If one of values is NAN then it is ignored. See also ranges.
-
-
-
-
-
MGL command: xrangedat [add=off]
-
MGL command: yrangedat [add=off]
-
MGL command: zrangedat [add=off]
-
MGL command: crangedat [add=off]
-
Sets the range for `x`-,`y`-,`z`- coordinate or coloring (`c`) as minimal and maximal values of data dat. Parameter add=on shows that the new range will be joined to existed one (not replace it).
-
-
-
-
MGL command: rangesx1 x2 y1 y2 [z1=0 z2=0]
-
Sets the ranges of coordinates. If minimal and maximal values of the coordinate are the same then they are ignored. Also it sets the range for coloring (analogous to crange z1 z2). This is default color range for 2d plots. Initial ranges are [-1, 1].
-
-
-
-
MGL command: rangesxx yy [zz cc=zz]
-
Sets the ranges of `x`-,`y`-,`z`-,`c`-coordinates and coloring as minimal and maximal values of data xx, yy, zz, cc correspondingly.
-
-
-
-
-
MGL command: originx0 y0 [z0=nan]
-
Sets center of axis cross section. If one of values is NAN then MathGL try to select optimal axis position.
-
-
-
-
MGL command: zoomaxisx1 x2
-
MGL command: zoomaxisx1 y1 x2 y2
-
MGL command: zoomaxisx1 y1 z1 x2 y2 z2
-
MGL command: zoomaxisx1 y1 z1 c1 x2 y2 z2 c2
-
Additionally extend axis range for any settings made by SetRange or SetRanges functions according the formula min += (max-min)*p1 and max += (max-min)*p1 (or min *= (max/min)^p1 and max *= (max/min)^p1 for log-axis range when inf>max/min>100 or 0<max/min<0.01). Initial ranges are [0, 1]. Attention! this settings can not be overwritten by any other functions, including DefaultPlotParam().
-
Sets transformation formulas for curvilinear coordinate. Each string should contain mathematical expression for real coordinate depending on internal coordinates `x`, `y`, `z` and `a` or `c` for colorbar. For example, the cylindrical coordinates are introduced as SetFunc("x*cos(y)", "x*sin(y)", "z");. For removing of formulas the corresponding parameter should be empty or NULL. Using transformation formulas will slightly slowing the program. Parameter EqA set the similar transformation formula for color scheme. See Textual formulas.
-
-
-
-
MGL command: axishow
-
Sets one of the predefined transformation formulas for curvilinear coordinate. Parameter how define the coordinates:
-
-
mglCartesian=0
-
Cartesian coordinates (no transformation, {x,y,z});
-
The function sets to draws Ternary (tern=1), Quaternary (tern=2) plot or projections (tern=4,5,6).
-
-
Ternary plot is special plot for 3 dependent coordinates (components) a, b, c so that a+b+c=1. MathGL uses only 2 independent coordinates a=x and b=y since it is enough to plot everything. At this third coordinate z act as another parameter to produce contour lines, surfaces and so on.
-
-
Correspondingly, Quaternary plot is plot for 4 dependent coordinates a, b, c and d so that a+b+c+d=1. MathGL uses only 3 independent coordinates a=x, b=y and d=z since it is enough to plot everything.
-
-
Projections can be obtained by adding value 4 to tern argument. So, that tern=4 will draw projections in Cartesian coordinates, tern=5 will draw projections in Ternary coordinates, tern=6 will draw projections in Quaternary coordinates. If you add 8 instead of 4 then all text labels will not be printed on projections.
-
-
Use Ternary(0) for returning to usual axis. See Ternary axis, for sample code and picture. See Axis projection, for sample code and picture.
-
Set the ticks step, number of sub-ticks and initial ticks position to be the most human readable for the axis along direction(s) dir. Also set SetTuneTicks(true). Usually you don`t need to call this function except the case of returning to default settings.
-
-
-
-
MGL command: xtickval [sub=0 org=nan 'fact'='']
-
MGL command: ytickval [sub=0 org=nan 'fact'='']
-
MGL command: ztickval [sub=0 org=nan 'fact'='']
-
MGL command: ctickval [sub=0 org=nan 'fact'='']
-
Set the ticks step d, number of sub-ticks ns (used for positive d) and initial ticks position org for the axis along direction dir (use `c` for colorbar ticks). Variable d set step for axis ticks (if positive) or it`s number on the axis range (if negative). Zero value set automatic ticks. If org value is NAN then axis origin is used. Parameter fact set text which will be printed after tick label (like "\pi" for d=M_PI).
-
-
-
-
MGL command: xtickval1 'lbl1' [val2 'lbl2' ...]
-
MGL command: ytickval1 'lbl1' [val2 'lbl2' ...]
-
MGL command: ztickval1 'lbl1' [val2 'lbl2' ...]
-
MGL command: xtickvdat 'lbls' [add=off]
-
MGL command: ytickvdat 'lbls' [add=off]
-
MGL command: ztickvdat 'lbls' [add=off]
-
Set the manual positions val and its labels lbl for ticks along axis dir. If array val is absent then values equidistantly distributed in x-axis range are used. Labels are separated by `\n` symbol. If only one value is specified in MGL command then the label will be add to the current ones. Use SetTicks() to restore automatic ticks.
-
-
-
-
-
MGL command: xtick'templ'
-
MGL command: ytick'templ'
-
MGL command: ztick'templ'
-
MGL command: ctick'templ'
-
Set template templ for x-,y-,z-axis ticks or colorbar ticks. It may contain TeX symbols also. If templ="" then default template is used (in simplest case it is `%.2g`). If template start with `&` symbol then long integer value will be passed instead of default type double. Setting on template switch off automatic ticks tuning.
-
-
-
-
MGL command: ticktime'dir' [dv=0 'tmpl'='']
-
Sets time labels with step val and template templ for x-,y-,z-axis ticks or colorbar ticks. It may contain TeX symbols also. The format of template templ is the same as described in http://www.manpagez.com/man/3/strftime/. Most common variants are `%X` for national representation of time, `%x` for national representation of date, `%Y` for year with century. If val=0 and/or templ="" then automatic tick step and/or template will be selected. You can use mgl_get_time() function for obtaining number of second for given date/time string. Note, that MS Visual Studio couldn`t handle date before 1970.
-
-
-
-
-
MGL command: tuneticksval [pos=1.15]
-
Switch on/off ticks enhancing by factoring common multiplier (for small, like from 0.001 to 0.002, or large, like from 1000 to 2000, coordinate values - enabled if tune&1 is nonzero) or common component (for narrow range, like from 0.999 to 1.000 - enabled if tune&2 is nonzero). Also set the position pos of common multiplier/component on the axis: =0 at minimal axis value, =1 at maximal axis value. Default value is 1.15.
-
-
-
-
MGL command: tickshiftdx [dy=0 dz=0 dc=0]
-
Set value of additional shift for ticks labels.
-
-
-
-
-
MGL command: origintickval
-
Enable/disable drawing of ticks labels at axis origin. In C/Fortran you can use mgl_set_flag(gr,val, MGL_NO_ORIGIN);.
-
-
-
-
MGL command: ticklenval [stt=1]
-
The relative length of axis ticks. Default value is 0.1. Parameter stt>0 set relative length of subticks which is in sqrt(1+stt) times smaller.
-
-
-
-
MGL command: axisstl'stl' ['tck'='' 'sub'='']
-
The line style of axis (stl), ticks (tck) and subticks (sub). If stl is empty then default style is used (`k` or `w` depending on transparency type). If tck or sub is empty then axis style is used (i.e. stl).
-
These functions control how and where further plotting will be placed. There is a certain calling order of these functions for the better plot appearance. First one should be subplot, multiplot or inplot for specifying the place. Second one can be title for adding title for the subplot. After it a rotate, shear and aspect. And finally any other plotting functions may be called. Alternatively you can use columnplot, gridplot, stickplot, shearplot or relative inplot for positioning plots in the column (or grid, or stick) one by another without gap between plot axis (bounding boxes). See Subplots, for sample code and picture.
-
-
-
MGL command: subplotnx ny m ['stl'='<>_^' dx=0 dy=0]
-
Puts further plotting in a m-th cell of nx*ny grid of the whole frame area. The position of the cell can be shifted from its default position by relative size dx, dy. This function set off any aspects or rotations. So it should be used first for creating the subplot. Extra space will be reserved for axis/colorbar if stl contain:
-
-
`L` or `<` - at left side,
-
`R` or `>` - at right side,
-
`A` or `^` - at top side,
-
`U` or `_` - at bottom side,
-
`#` - reserve none space (use whole region for axis range) - axis and tick labels will be invisible by default.
-
-
From the aesthetical point of view it is not recommended to use this function with different matrices in the same frame. Note, colorbar can be invisible (be out of image borders) if you set empty style ``.
-
-
-
-
MGL command: multiplotnx ny m dx dy ['style'='<>_^' sx sy]
-
Puts further plotting in a rectangle of dx*dy cells starting from m-th cell of nx*ny grid of the whole frame area. The position of the rectangular area can be shifted from its default position by relative size sx, sy. This function set off any aspects or rotations. So it should be used first for creating subplot. Extra space will be reserved for axis/colorbar if stl contain:
-
-
`L` or `<` - at left side,
-
`R` or `>` - at right side,
-
`A` or `^` - at top side,
-
`U` or `_` - at bottom side.
-`#` - reserve none space (use whole region for axis range) - axis and tick labels will be invisible by default.
-
-
-
-
-
MGL command: inplotx1 x2 y1 y2 [rel=on]
-
Puts further plotting in some region of the whole frame surface. This function allows one to create a plot in arbitrary place of the screen. The position is defined by rectangular coordinates [x1, x2]*[y1, y2]. The coordinates x1, x2, y1, y2 are normalized to interval [0, 1]. If parameter rel=true then the relative position to current subplot (or inplot with rel=false) is used. This function set off any aspects or rotations. So it should be used first for creating subplot.
-
-
-
-
MGL command: columnplotnum ind [d=0]
-
Puts further plotting in ind-th cell of column with num cells. The position is relative to previous subplot (or inplot with rel=false). Parameter d set extra gap between cells.
-
-
-
-
MGL command: gridplotnx ny ind [d=0]
-
Puts further plotting in ind-th cell of nx*ny grid. The position is relative to previous subplot (or inplot with rel=false). Parameter d set extra gap between cells.
-
-
-
-
MGL command: stickplotnum ind tet phi
-
Puts further plotting in ind-th cell of stick with num cells. At this, stick is rotated on angles tet, phi. The position is relative to previous subplot (or inplot with rel=false).
-
-
-
-
MGL command: shearplotnum ind sx sy [xd yd]
-
Puts further plotting in ind-th cell of stick with num cells. At this, cell is sheared on values sx, sy. Stick direction is specified be xd and yd. The position is relative to previous subplot (or inplot with rel=false).
-
-
-
-
-
MGL command: title'title' ['stl'='' size=-2]
-
Add text title for current subplot/inplot. Parameter stl can contain:
-
Parameter size set font size. This function set off any aspects or rotations. So it should be used just after creating subplot.
-
-
-
-
MGL command: rotatetetx tetz [tety=0]
-
Rotates a further plotting relative to each axis {x, z, y} consecutively on angles TetX, TetZ, TetY.
-
-
-
-
MGL command: rotatetet x y z
-
Rotates a further plotting around vector {x, y, z} on angle Tet.
-
-
-
-
MGL command: shearsx sy
-
Shears a further plotting on values sx, sy.
-
-
-
-
MGL command: aspectax ay [az=1]
-
Defines aspect ratio for the plot. The viewable axes will be related one to another as the ratio Ax:Ay:Az. For the best effect it should be used after rotate function. If Ax is NAN then function try to select optimal aspect ratio to keep equal ranges for x-y axis. At this, Ay will specify proportionality factor, or set to use automatic one if Ay=NAN.
-
-
-
-
There are 3 functions View(), Zoom() and Perspective() which transform whole image. I.e. they act as secondary transformation matrix. They were introduced for rotating/zooming the whole plot by mouse. It is not recommended to call them for picture drawing.
-
-
-
MGL command: perspectiveval
-
Add (switch on) the perspective to plot. The parameter a = Depth/(Depth+dz) \in [0,1). By default (a=0) the perspective is off.
-
-
-
-
MGL command: viewtetx tetz [tety=0]
-
Rotates a further plotting relative to each axis {x, z, y} consecutively on angles TetX, TetZ, TetY. Rotation is done independently on rotate. Attention! this settings can not be overwritten by DefaultPlotParam(). Use Zoom(0,0,1,1) to return default view.
-
-
-
-
MGL command: zoomx1 y1 x2 y2
-
The function changes the scale of graphics that correspond to zoom in/out of the picture. After function call the current plot will be cleared and further the picture will contain plotting from its part [x1,x2]*[y1,y2]. Here picture coordinates x1, x2, y1, y2 changes from 0 to 1. Attention! this settings can not be overwritten by any other functions, including DefaultPlotParam(). Use Zoom(0,0,1,1) to return default view.
-
Functions in this group save or give access to produced picture. So, usually they should be called after plotting is done.
-
-
-
MGL command: setsizew h
-
Sets size of picture in pixels. This function should be called before any other plotting because it completely remove picture contents if clear=true. Function just clear pixels and scale all primitives if clear=false.
-
-
-
-
MGL command: setsizesclfactor
-
Set factor for width and height in all further calls of setsize. This command is obsolete since v.2.4.2.
-
-
-
-
MGL command: quality[val=2]
-
Sets quality of the plot depending on value val: MGL_DRAW_WIRE=0 - no face drawing (fastest), MGL_DRAW_FAST=1 - no color interpolation (fast), MGL_DRAW_NORM=2 - high quality (normal), MGL_DRAW_HIGH=3 - high quality with 3d primitives (arrows and marks); MGL_DRAW_LMEM=0x4 - direct bitmap drawing (low memory usage); MGL_DRAW_DOTS=0x8 - for dots drawing instead of primitives (extremely fast).
-
These functions export current view to a graphic file. The filename fname should have appropriate extension. Parameter descr gives the short description of the picture. Just now the transparency is supported in PNG, SVG, OBJ and PRC files.
-
-
-
MGL command: write['fname'='']
-
Exports current frame to a file fname which type is determined by the extension. Parameter descr adds description to file (can be ""). If fname="" then the file `frame####.jpg` is used, where `####` is current frame id and name `frame` is defined by plotid class property.
-
-
-
-
MGL command: bboxx1 y1 [x2=-1 y2=-1]
-
Set boundary box for export graphics into 2D file formats. If x2<0 (y2<0) then original image width (height) will be used. If x1<0 or y1<0 or x1>=x2|Width or y1>=y2|Height then cropping will be disabled.
-
There are no commands for making animation in MGL. However you can use features of mglconv and mglview utilities. For example, by busing special comments `##a ` or `##c `.
-
Clear the picture and fill background by specified color.
-
-
-
-
MGL command: rasterize
-
Force drawing the plot and use it as background. After it, function clear the list of primitives, like clf. This function is useful if you want save part of plot as bitmap one (for example, large surfaces, isosurfaces or vector fields) and keep some parts as vector one (like annotation, curves, axis and so on).
-
-
-
-
MGL command: background'fname' [alpha=1]
-
Load PNG or JPEG file fname as background for the plot. Parameter alpha manually set transparency of the background.
-
These functions draw some simple objects like line, point, sphere, drop, cone and so on. See Using primitives, for sample code and picture.
-
-
-
MGL command: ballx y ['col'='r.']
-
MGL command: ballx y z ['col'='r.']
-
Draws a mark (point `.` by default) at position p={x, y, z} with color col.
-
-
-
-
MGL command: errboxx y ex ey ['stl'='']
-
MGL command: errboxx y z ex ey ez ['stl'='']
-
Draws a 3d error box at position p={x, y, z} with sizes e={ex, ey, ez} and style stl. Use NAN for component of e to reduce number of drawn elements.
-
-
-
-
MGL command: linex1 y1 x2 y2 ['stl'='']
-
MGL command: linex1 y1 z1 x2 y2 z2 ['stl'='']
-
Draws a geodesic line (straight line in Cartesian coordinates) from point p1 to p2 using line style stl. Parameter num define the “quality” of the line. If num=2 then the straight line will be drawn in all coordinate system (independently on transformation formulas (see Curved coordinates). Contrary, for large values (for example, =100) the geodesic line will be drawn in corresponding coordinate system (straight line in Cartesian coordinates, circle in polar coordinates and so on). Line will be drawn even if it lies out of bounding box.
-
Draws Bezier-like curve from point p1 to p2 using line style stl. At this tangent is codirected with d1, d2 and proportional to its amplitude. Parameter num define the “quality” of the curve. If num=2 then the straight line will be drawn in all coordinate system (independently on transformation formulas, see Curved coordinates). Contrary, for large values (for example, =100) the spline like Bezier curve will be drawn in corresponding coordinate system. Curve will be drawn even if it lies out of bounding box.
-
Draws the solid quadrangle (face) with vertexes p1, p2, p3, p4 and with color(s) stl. At this colors can be the same for all vertexes or different if all 4 colors are specified for each vertex. Face will be drawn even if it lies out of bounding box.
-
-
-
-
MGL command: rectx1 y1 x2 y2 ['stl'='']
-
MGL command: rectx1 y1 z1 x2 y2 z2 ['stl'='']
-
Draws the solid rectangle (face) with vertexes {x1, y1, z1} and {x2, y2, z2} with color stl. At this colors can be the same for all vertexes or separately if all 4 colors are specified for each vertex. Face will be drawn even if it lies out of bounding box.
-
Draws the solid rectangle (face) perpendicular to [x,y,z]-axis correspondingly at position {x0, y0, z0} with color stl and with widths wx, wy, wz along corresponding directions. At this colors can be the same for all vertexes or separately if all 4 colors are specified for each vertex. Parameters d1!=0, d2!=0 set additional shift of the last vertex (i.e. to draw quadrangle). Face will be drawn even if it lies out of bounding box.
-
-
-
-
MGL command: spherex0 y0 r ['col'='r']
-
MGL command: spherex0 y0 z0 r ['col'='r']
-
Draw the sphere with radius r and center at point p={x0, y0, z0} and color stl.
-
-
-
-
MGL command: dropx0 y0 dx dy r ['col'='r' sh=1 asp=1]
-
MGL command: dropx0 y0 z0 dx dy dz r ['col'='r' sh=1 asp=1]
-
Draw the drop with radius r at point p elongated in direction d and with color col. Parameter shift set the degree of drop oblongness: `0` is sphere, `1` is maximally oblongness drop. Parameter ap set relative width of the drop (this is analogue of “ellipticity” for the sphere).
-
Draw tube (or truncated cone if edge=false) between points p1, p2 with radius at the edges r1, r2. If r2<0 then it is supposed that r2=r1. The cone color is defined by string stl. Parameter stl can contain:
-
-
`@` for drawing edges;
-
`#` for wired cones;
-
`t` for drawing tubes/cylinder instead of cones/prisms;
-
`4`, `6`, `8` for drawing square, hex- or octo-prism instead of cones.
-
-
-
-
-
MGL command: circlex0 y0 r ['col'='r']
-
MGL command: circlex0 y0 z0 r ['col'='r']
-
Draw the circle with radius r and center at point p={x0, y0, z0}. Parameter col may contain
-
-
colors for filling and boundary (second one if style `@` is used, black color is used by default);
-
`#` for wire figure (boundary only);
-
`@` for filling and boundary.
-
-
-
-
-
MGL command: ellipsex1 y1 x2 y2 r ['col'='r']
-
MGL command: ellipsex1 y1 z1 x2 y2 z2 r ['col'='r']
-
Draw the ellipse with radius r and focal points p1, p2. Parameter col may contain
-
-
colors for filling and boundary (second one if style `@` is used, black color is used by default);
-
`#` for wire figure (boundary only);
-
`@` for filling and boundary.
-
-
-
-
-
MGL command: rhombx1 y1 x2 y2 r ['col'='r']
-
MGL command: rhombx1 y1 z1 x2 y2 z2 r ['col'='r']
-
Draw the rhombus with width r and edge points p1, p2. Parameter col may contain
-
-
colors for filling and boundary (second one if style `@` is used, black color is used by default);
-
`#` for wire figure (boundary only);
-
`@` for filling and boundary.
-
-
-
-
-
MGL command: arcx0 y0 x1 y1 a ['col'='r']
-
MGL command: arcx0 y0 z0 x1 y1 a ['col'='r']
-
MGL command: arcx0 y0 z0 xa ya za x1 y1 z1 a ['col'='r']
-
Draw the arc around axis pa (default is z-axis pa={0,0,1}) with center at p0 and starting from point p1. Parameter a set the angle of arc in degree. Parameter col may contain color of the arc and arrow style for arc edges.
-
-
-
-
MGL command: polygonx0 y0 x1 y1 num ['col'='r']
-
MGL command: polygonx0 y0 z0 x1 y1 z1 num ['col'='r']
-
Draw the polygon with num edges starting from p1. The center of polygon is located in p0. Parameter col may contain
-
-
colors for filling and boundary (second one if style `@` is used, black color is used by default);
-
`#` for wire figure (boundary only);
-
`@` for filling and boundary.
-
-
-
-
-
-
MGL command: logo'fname' [smooth=off]
-
Draw bitmap (logo) along whole axis range, which can be changed by Command options. Bitmap can be loaded from file or specified as RGBA values for pixels. Parameter smooth set to draw bitmap without or with color interpolation.
-
-
-
-
-
MGL command: symbolx y 'id' ['fnt'='' size=-1]
-
MGL command: symbolx y z 'id' ['fnt'='' size=-1]
-
Draws user-defined symbol with name id at position p with style specifying by fnt. The size of font is set by size parameter (default is -1). The string fnt may contain color specification ended by `:` symbol; styles `a`, `A` to draw at absolute position {x, y} (supposed to be in range [0,1]) of picture (for `A`) or subplot/inplot (for `a`); and style `w` to draw wired symbol.
-
-
-
-
MGL command: symbolx y dx dy 'id' ['fnt'=':L' size=-1]
-
MGL command: symbolx y z dx dy dz 'id' ['fnt'=':L' size=-1]
-
The same as previous but symbol will be drawn rotated along direction d.
-
-
-
-
MGL command: addsymbol'id' xdat ydat
-
Add user-defined symbol with name id and contour {xdat, ydat}. You can use NAN values to set break (jump) of contour curve.
-
These functions draw the text. There are functions for drawing text in arbitrary place, in arbitrary direction and along arbitrary curve. MathGL can use arbitrary font-faces and parse many TeX commands (for more details see Font styles). All these functions have 2 variant: for printing 8-bit text (char *) and for printing Unicode text (wchar_t *). In first case the conversion into the current locale is used. So sometimes you need to specify it by setlocale() function. The size argument control the size of text: if positive it give the value, if negative it give the value relative to SetFontSize(). The font type (STIX, arial, courier, times and so on) can be selected by function LoadFont(). See Font settings.
-
-
The font parameters are described by string. This string may set the text color `wkrgbcymhRGBCYMHW` (see Color styles). Starting from MathGL v.2.3, you can set color gradient for text (see Color scheme). Also, after delimiter symbol `:`, it can contain characters of font type (`rbiwou`) and/or align (`LRCTV`) specification. The font types are: `r` - roman (or regular) font, `i` - italic style, `b` - bold style, `w` - wired style, `o` - over-lined text, `u` - underlined text. By default roman font is used. The align types are: `L` - align left (default), `C` - align center, `R` - align right, `T` - align under, `V` - align center vertical. For example, string `b:iC` correspond to italic font style for centered text which printed by blue color.
-
-
If string contains symbols `aA` then text is printed at absolute position {x, y} (supposed to be in range [0,1]) of picture (for `A`) or subplot/inplot (for `a`). If string contains symbol `@` then box around text is drawn.
-
Draws the string text at position p with fonts specifying by the criteria fnt. The size of font is set by size parameter (default is -1).
-
-
-
-
MGL command: textx y dx dy 'text' ['fnt'=':L' size=-1]
-
MGL command: textx y z dx dy dz 'text' ['fnt'=':L' size=-1]
-
Draws the string text at position p along direction d with specified size. Parameter fnt set text style and text position: under (`T`) or above (`t`) the line.
-
-
-
-
MGL command: fgetsx y 'fname' [n=0 'fnt'='' size=-1.4]
-
MGL command: fgetsx y z 'fname' [n=0 'fnt'='' size=-1.4]
-
Draws unrotated n-th line of file fname at position {x,y,z} with specified size. By default parameters from font command are used.
-
-
-
-
MGL command: textydat 'text' ['fnt'='']
-
MGL command: textxdat ydat 'text' ['fnt'='']
-
MGL command: textxdat ydat zdat 'text' ['fnt'='']
-
The function draws text along the curve between points {x[i], y[i], z[i]} by font style fnt. The string fnt may contain symbols `t` for printing the text under the curve (default), or `T` for printing the text under the curve. The sizes of 1st dimension must be equal for all arrays x.nx=y.nx=z.nx. If array x is not specified then its an automatic array is used with values equidistantly distributed in x-axis range (see Ranges (bounding box)). If array z is not specified then z[i] equal to minimal z-axis value is used. String opt contain command options (see Command options).
-
These functions draw the “things for measuring”, like axis with ticks, colorbar with ticks, grid along axis, bounding box and labels for axis. For more information see Axis settings.
-
-
-
MGL command: axis['dir'='xyz' 'stl'='']
-
Draws axes with ticks (see Axis settings). Parameter dir may contain:
-
-
`xyz` for drawing axis in corresponding direction;
-
`XYZ` for drawing axis in corresponding direction but with inverted positions of labels;
-
`AKDTVISO` for drawing arrow at the end of axis;
-
`a` for forced adjusting of axis ticks;
-
`:` for drawing lines through point (0,0,0);
-
`f` for printing ticks labels in fixed format;
-
`E` for using `E` instead of `e` in ticks labels;
-
`F` for printing ticks labels in LaTeX format;
-
`+` for printing `+` for positive ticks;
-
`-` for printing usual `-` in ticks labels;
-
`0123456789` for precision at printing ticks labels.
-
-
Styles of ticks and axis can be overrided by using stl string. Option value set the manual rotation angle for the ticks. See Axis and ticks, for sample code and picture.
-
The same as previous but with sharp colors sch (current palette if sch="") for values v. See contd sample, for sample code and picture.
-
-
-
-
MGL command: colorbar'sch' x y [w=1 h=1]
-
The same as first one but at arbitrary position of subplot {x, y} (supposed to be in range [0,1]). Parameters w, h set the relative width and height of the colorbar.
-
-
-
-
MGL command: colorbarvdat 'sch' x y [w=1 h=1]
-
The same as previous but with sharp colors sch (current palette if sch="") for values v. See contd sample, for sample code and picture.
-
-
-
-
MGL command: grid['dir'='xyz' 'pen'='B']
-
Draws grid lines perpendicular to direction determined by string parameter dir. If dir contain `!` then grid lines will be drawn at coordinates of subticks also. The step of grid lines is the same as tick step for axis. The style of lines is determined by pen parameter (default value is dark blue solid line `B-`).
-
-
-
-
MGL command: box['stl'='k' ticks=on]
-
Draws bounding box outside the plotting volume with color col. If col contain `@` then filled faces are drawn. At this first color is used for faces (default is light yellow), last one for edges. See Bounding box, for sample code and picture.
-
-
-
-
MGL command: xlabel'text' [pos=1]
-
MGL command: ylabel'text' [pos=1]
-
MGL command: zlabel'text' [pos=1]
-
MGL command: tlabel'text' [pos=1]
-
Prints the label text for axis dir=`x`,`y`,`z`,`t` (here `t` is “ternary” axis t=1-x-y). The position of label is determined by pos parameter. If pos=0 then label is printed at the center of axis. If pos>0 then label is printed at the maximum of axis. If pos<0 then label is printed at the minimum of axis. Option value set additional shifting of the label. See Text printing.
-
These functions draw legend to the graph (useful for 1D plotting). Legend entry is a pair of strings: one for style of the line, another one with description text (with included TeX parsing). The arrays of strings may be used directly or by accumulating first to the internal arrays (by function addlegend) and further plotting it. The position of the legend can be selected automatic or manually (even out of bounding box). Parameters fnt and size specify the font style and size (see Font settings). Option value set the relative width of the line sample and the text indent. If line style string for entry is empty then the corresponding text is printed without indent. Parameter fnt may contain:
-
-
font style for legend text;
-
`A` for positioning in absolute coordinates;
-
`^` for positioning outside of specified point;
-
`#` for drawing box around legend;
-
`-` for arranging legend entries horizontally;
-
colors for face (1st one), for border (2nd one) and for text (last one). If less than 3 colors are specified then the color for border is black (for 2 and less colors), and the color for face is white (for 1 or none colors).
-
Draws legend of accumulated legend entries by font fnt with size. Parameter pos sets the position of the legend: `0` is bottom left corner, `1` is bottom right corner, `2` is top left corner, `3` is top right corner (is default). Option value set the space between line samples and text (default is 0.1).
-
-
-
-
MGL command: legendx y ['fnt'='#']
-
Draws legend of accumulated legend entries by font fnt with size. Position of legend is determined by parameter x, y which supposed to be normalized to interval [0,1]. Option value set the space between line samples and text (default is 0.1).
-
-
-
-
MGL command: addlegend'text' 'stl'
-
Adds string text to internal legend accumulator. The style of described line and mark is specified in string style (see Line styles).
-
-
-
-
MGL command: clearlegend
-
Clears saved legend strings.
-
-
-
-
MGL command: legendmarksval
-
Set the number of marks in the legend. By default 1 mark is used.
-
These functions perform plotting of 1D data. 1D means that data depended from only 1 parameter like parametric curve {x[i],y[i],z[i]}, i=1...n. By default (if absent) values of x[i] are equidistantly distributed in axis range, and z[i] equal to minimal z-axis value. The plots are drawn for each row if one of the data is the matrix. By any case the sizes of 1st dimension must be equal for all arrays x.nx=y.nx=z.nx.
-
-
String pen specifies the color and style of line and marks (see Line styles). By default (pen="") solid line with color from palette is used (see Palette and colors). Symbol `!` set to use new color from palette for each point (not for each curve, as default). String opt contain command options (see Command options).
-
-
-
MGL command: plotydat ['stl'='']
-
MGL command: plotxdat ydat ['stl'='']
-
MGL command: plotxdat ydat zdat ['stl'='']
-
These functions draw continuous lines between points {x[i], y[i], z[i]}. If pen contain `a` then segments between points outside of axis range are drawn too. If pen contain `~` then number of segments is reduce for quasi-straight curves. See also area, step, stem, tube, mark, error, belt, tens, tape, meshnum. See plot sample, for sample code and picture.
-
-
-
-
MGL command: radaradat ['stl'='']
-
This functions draws radar chart which is continuous lines between points located on an radial lines (like plot in Polar coordinates). Option value set the additional shift of data (i.e. the data a+value is used instead of a). If value<0 then r=max(0, -min(value). If pen containt `#` symbol then "grid" (radial lines and circle for r) is drawn. If pen contain `a` then segments between points outside of axis range are drawn too. See also plot, meshnum. See radar sample, for sample code and picture.
-
-
-
-
MGL command: stepydat ['stl'='']
-
MGL command: stepxdat ydat ['stl'='']
-
MGL command: stepxdat ydat zdat ['stl'='']
-
These functions draw continuous stairs for points to axis plane. If x.nx>y.nx then x set the edges of bars, rather than its central positions. See also plot, stem, tile, boxs, meshnum. See step sample, for sample code and picture.
-
-
-
-
MGL command: tensydat cdat ['stl'='']
-
MGL command: tensxdat ydat cdat ['stl'='']
-
MGL command: tensxdat ydat zdat cdat ['stl'='']
-
These functions draw continuous lines between points {x[i], y[i], z[i]} with color defined by the special array c[i] (look like tension plot). String pen specifies the color scheme (see Color scheme) and style and/or width of line (see Line styles). If pen contain `a` then segments between points outside of axis range are drawn too. If pen contain `~` then number of segments is reduce for quasi-straight curves. See also plot, mesh, fall, meshnum. See tens sample, for sample code and picture.
-
-
-
-
MGL command: tapeydat ['stl'='']
-
MGL command: tapexdat ydat ['stl'='']
-
MGL command: tapexdat ydat zdat ['stl'='']
-
These functions draw tapes of normals for curve between points {x[i], y[i], z[i]}. Initial tape(s) was selected in x-y plane (for `x` in pen) and/or y-z plane (for `x` in pen). The width of tape is proportional to barwidth and can be changed by option value. See also plot, flow, barwidth. See tape sample, for sample code and picture.
-
-
-
-
MGL command: areaydat ['stl'='']
-
MGL command: areaxdat ydat ['stl'='']
-
MGL command: areaxdat ydat zdat ['stl'='']
-
These functions draw continuous lines between points and fills it to axis plane. Also you can use gradient filling if number of specified colors is equal to 2*number of curves. If pen contain `#` then wired plot is drawn. If pen contain `a` then segments between points outside of axis range are drawn too. See also plot, bars, stem, region. See area sample, for sample code and picture.
-
These functions fill area between 2 curves. Dimensions of arrays y1 and y2 must be equal. Also you can use gradient filling if number of specified colors is equal to 2*number of curves. If for 2D version pen contain symbol `i` then only area with y1<y<y2 will be filled else the area with y2<y<y1 will be filled too. If pen contain `#` then wired plot is drawn. If pen contain `a` then segments between points outside of axis range are drawn too. See also area, bars, stem. See region sample, for sample code and picture.
-
-
-
-
MGL command: stemydat ['stl'='']
-
MGL command: stemxdat ydat ['stl'='']
-
MGL command: stemxdat ydat zdat ['stl'='']
-
These functions draw vertical lines from points to axis plane. See also area, bars, plot, mark. See stem sample, for sample code and picture.
-
-
-
-
MGL command: barsydat ['stl'='']
-
MGL command: barsxdat ydat ['stl'='']
-
MGL command: barsxdat ydat zdat ['stl'='']
-
These functions draw vertical bars from points to axis plane. Parameter pen can contain:
-
-
`a` for drawing lines one above another (like summation);
-
`f` for drawing waterfall chart, which show the cumulative effect of sequential positive or negative values;
-
`F` for using fixed (minimal) width for all bars;
-
`<`, `^` or `>` for aligning boxes left, right or centering them at its x-coordinates.
-
-
You can give different colors for positive and negative values if number of specified colors is equal to 2*number of curves. If x.nx>y.nx then x set the edges of bars, rather than its central positions. See also barh, cones, area, stem, chart, barwidth. See bars sample, for sample code and picture.
-
-
-
-
MGL command: barhvdat ['stl'='']
-
MGL command: barhydat vdat ['stl'='']
-
These functions draw horizontal bars from points to axis plane. Parameter pen can contain:
-
-
`a` for drawing lines one above another (like summation);
-
`f` for drawing waterfall chart, which show the cumulative effect of sequential positive or negative values;
-
`F` for using fixed (minimal) width for all bars;
-
`<`, `^` or `>` for aligning boxes left, right or centering them at its x-coordinates.
-
-
You can give different colors for positive and negative values if number of specified colors is equal to 2*number of curves. If x.nx>y.nx then x set the edges of bars, rather than its central positions. See also bars, barwidth. See barh sample, for sample code and picture.
-
-
-
-
MGL command: conesydat ['stl'='']
-
MGL command: conesxdat ydat ['stl'='']
-
MGL command: conesxdat ydat zdat ['stl'='']
-
These functions draw cones from points to axis plane. If string contain symbol `a` then cones are drawn one above another (like summation). You can give different colors for positive and negative values if number of specified colors is equal to 2*number of curves. Parameter pen can contain:
-
-
`@` for drawing edges;
-
`#` for wired cones;
-
`t` for drawing tubes/cylinders instead of cones/prisms;
-
`4`, `6`, `8` for drawing square, hex- or octo-prism instead of cones;
-
`<`, `^` or `>` for aligning boxes left, right or centering them at its x-coordinates.
-
The function draws colored stripes (boxes) for data in array a. The number of stripes is equal to the number of rows in a (equal to a.ny). The color of each next stripe is cyclically changed from colors specified in string col or in palette Pal (see Palette and colors). Spaces in colors denote transparent “color” (i.e. corresponding stripe(s) are not drawn). The stripe width is proportional to value of element in a. Chart is plotted only for data with non-negative elements. If string col have symbol `#` then black border lines are drawn. The most nice form the chart have in 3d (after rotation of coordinates) or in cylindrical coordinates (becomes so called Pie chart). See chart sample, for sample code and picture.
-
-
-
-
MGL command: boxplotadat ['stl'='']
-
MGL command: boxplotxdat adat ['stl'='']
-
These functions draw boxplot (also known as a box-and-whisker diagram) at points x[i]. This is five-number summaries of data a[i,j] (minimum, lower quartile (Q1), median (Q2), upper quartile (Q3) and maximum) along second (j-th) direction. If pen contain `<`, `^` or `>` then boxes will be aligned left, right or centered at its x-coordinates. See also plot, error, bars, barwidth. See boxplot sample, for sample code and picture.
-
These functions draw candlestick chart at points x[i]. This is a combination of a line-chart and a bar-chart, in that each bar represents the range of price movement over a given time interval. Wire (or white) candle correspond to price growth v1[i]<v2[i], opposite case - solid (or dark) candle. You can give different colors for growth and decrease values if number of specified colors is equal to 2. If pen contain `#` then the wire candle will be used even for 2-color scheme. "Shadows" show the minimal y1 and maximal y2 prices. If v2 is absent then it is determined as v2[i]=v1[i+1]. See also plot, bars, ohlc, barwidth. See candle sample, for sample code and picture.
-
These functions draw Open-High-Low-Close diagram. This diagram show vertical line for between maximal(high h) and minimal(low l) values, as well as horizontal lines before/after vertical line for initial(open o)/final(close c) values of some process (usually price). You can give different colors for up and down values (when closing values higher or not as in previous point) if number of specified colors is equal to 2*number of curves. See also candle, plot, barwidth. See ohlc sample, for sample code and picture.
-
-
-
-
-
MGL command: errorydat yerr ['stl'='']
-
MGL command: errorxdat ydat yerr ['stl'='']
-
MGL command: errorxdat ydat xerr yerr ['stl'='']
-
These functions draw error boxes {ex[i], ey[i]} at points {x[i], y[i]}. This can be useful, for example, in experimental points, or to show numeric error or some estimations and so on. If string pen contain symbol `@` than large semitransparent mark is used instead of error box. See also plot, mark. See error sample, for sample code and picture.
-
-
-
-
MGL command: markydat rdat ['stl'='']
-
MGL command: markxdat ydat rdat ['stl'='']
-
MGL command: markxdat ydat zdat rdat ['stl'='']
-
These functions draw marks with size r[i]*marksize at points {x[i], y[i], z[i]}. If you need to draw markers of the same size then you can use plot function with empty line style ``. For markers with size in axis range use error with style `@`. See also plot, textmark, error, stem, meshnum. See mark sample, for sample code and picture.
-
These functions draw string txt as marks with size proportional to r[i]*marksize at points {x[i], y[i], z[i]}. By default (if omitted) r[i]=1. See also plot, mark, stem, meshnum. See textmark sample, for sample code and picture.
-
-
-
-
MGL command: labelydat 'txt' ['stl'='']
-
MGL command: labelxdat ydat 'txt' ['stl'='']
-
MGL command: labelxdat ydat zdat 'txt' ['stl'='']
-
These functions draw string txt at points {x[i], y[i], z[i]}. If string txt contain `%x`, `%y`, `%z` or `%n` then it will be replaced by the value of x-,y-,z-coordinate of the point or its index. String fnt may contain:
-
These functions draw table with values of val and captions from string txt (separated by newline symbol `\n`) at points {x, y} (default at {0,0}) related to current subplot. String fnt may contain:
-
`|` for limiting table widh by subplot one (equal to option `value 1`);
-
`=` for equal width of all cells;
-
`f` for fixed format of printed numbers;
-
`E` for using `E` instead of `e`;
-
`F` for printing in LaTeX format;
-
`+` for printing `+` for positive numbers;
-
`-` for printing usual `-`;
-
`0123456789` for precision at printing numbers.
-
-
Option value set the width of the table (default is 1). See also plot, label. See table sample, for sample code and picture.
-
-
-
-
MGL command: irisdats 'ids' ['stl'='']
-
MGL command: irisdats rngs 'ids' ['stl'='']
-
Draws Iris plots for determining cross-dependences of data arrays dats (see http://en.wikipedia.org/wiki/Iris_flower_data_set). Data rngs of size 2*dats.nx provide manual axis ranges for each column. String ids contain column names, separated by `;` symbol. Option value set the text size for column names. You can add another data set to existing Iris plot by providing the same ranges rngs and empty column names ids. See also plot. See iris sample, for sample code and picture.
-
-
-
-
MGL command: tubeydat rdat ['stl'='']
-
MGL command: tubeydat rval ['stl'='']
-
MGL command: tubexdat ydat rdat ['stl'='']
-
MGL command: tubexdat ydat rval ['stl'='']
-
MGL command: tubexdat ydat zdat rdat ['stl'='']
-
MGL command: tubexdat ydat zdat rval ['stl'='']
-
These functions draw the tube with variable radius r[i] along the curve between points {x[i], y[i], z[i]}. Option value set the number of segments at cross-section (default is 25). See also plot. See tube sample, for sample code and picture.
-
-
-
-
MGL command: torusrdat zdat ['stl'='']
-
These functions draw surface which is result of curve {r, z} rotation around axis. If string pen contain symbols `x` or `z` then rotation axis will be set to specified direction (default is `y`). If string pen have symbol `#` then wire plot is produced. If string pen have symbol `.` then plot by dots is produced. See also plot, axial. See torus sample, for sample code and picture.
-
-
-
-
MGL command: lamereyx0 ydat ['stl'='']
-
MGL command: lamereyx0 'y(x)' ['stl'='']
-
These functions draw Lamerey diagram for mapping x_new = y(x_old) starting from point x0. String stl may contain line style, symbol `v` for drawing arrows, symbol `~` for disabling first segment. Option value set the number of segments to be drawn (default is 20). See also plot, fplot, bifurcation, pmap. See lamerey sample, for sample code and picture.
-
-
-
-
MGL command: bifurcationdx ydat ['stl'='']
-
MGL command: bifurcationdx 'y(x)' ['stl'='']
-
These functions draw bifurcation diagram for mapping x_new = y(x_old). Parameter dx set the accuracy along x-direction. String stl set color. Option value set the number of stationary points (default is 1024). See also plot, fplot, lamerey. See bifurcation sample, for sample code and picture.
-
-
-
-
MGL command: pmapydat sdat ['stl'='']
-
MGL command: pmapxdat ydat sdat ['stl'='']
-
MGL command: pmapxdat ydat zdat sdat ['stl'='']
-
These functions draw Poincare map for curve {x, y, z} at surface s=0. Basically, it show intersections of the curve and the surface. String stl set the style of marks. See also plot, mark, lamerey. See pmap sample, for sample code and picture.
-
These functions perform plotting of 2D data. 2D means that data depend from 2 independent parameters like matrix f(x_i,y_j), i=1...n, j=1...m. By default (if absent) values of x, y are equidistantly distributed in axis range. The plots are drawn for each z slice of the data. The minor dimensions of arrays x, y, z should be equal x.nx=z.nx && y.nx=z.ny or x.nx=y.nx=z.nx && x.ny=y.ny=z.ny. Arrays x and y can be vectors (not matrices as z). String sch sets the color scheme (see Color scheme) for plot. String opt contain command options (see Command options).
-
-
-
MGL command: surfzdat ['sch'='']
-
MGL command: surfxdat ydat zdat ['sch'='']
-
The function draws surface specified parametrically {x[i,j], y[i,j], z[i,j]}. If string sch have symbol `#` then grid lines are drawn. If string sch have symbol `.` then plot by dots is produced. See also mesh, dens, belt, tile, boxs, surfc, surfa. See surf sample, for sample code and picture.
-
-
-
-
MGL command: meshzdat ['sch'='']
-
MGL command: meshxdat ydat zdat ['sch'='']
-
The function draws mesh lines for surface specified parametrically {x[i,j], y[i,j], z[i,j]}. See also surf, fall, meshnum, cont, tens. See mesh sample, for sample code and picture.
-
-
-
-
MGL command: fallzdat ['sch'='']
-
MGL command: fallxdat ydat zdat ['sch'='']
-
The function draws fall lines for surface specified parametrically {x[i,j], y[i,j], z[i,j]}. This plot can be used for plotting several curves shifted in depth one from another. If sch contain `x` then lines are drawn along x-direction else (by default) lines are drawn along y-direction. See also belt, mesh, tens, meshnum. See fall sample, for sample code and picture.
-
-
-
-
MGL command: beltzdat ['sch'='']
-
MGL command: beltxdat ydat zdat ['sch'='']
-
The function draws belts for surface specified parametrically {x[i,j], y[i,j], z[i,j]}. This plot can be used as 3d generalization of plot). If sch contain `x` then belts are drawn along x-direction else (by default) belts are drawn along y-direction. See also fall, surf, beltc, plot, meshnum. See belt sample, for sample code and picture.
-
-
-
-
MGL command: boxszdat ['sch'='']
-
MGL command: boxsxdat ydat zdat ['sch'='']
-
The function draws vertical boxes for surface specified parametrically {x[i,j], y[i,j], z[i,j]}. Symbol `@` in sch set to draw filled boxes. See also surf, dens, tile, step. See boxs sample, for sample code and picture.
-
-
-
-
MGL command: tilezdat ['sch'='']
-
MGL command: tilexdat ydat zdat ['sch'='']
-
MGL command: tilexdat ydat zdat cdat ['sch'='']
-
The function draws horizontal tiles for surface specified parametrically {x[i,j], y[i,j], z[i,j]} and color it by matrix c[i,j] (c=z if c is not provided). If string sch contain style `x` or `y` then tiles will be oriented perpendicular to x- or y-axis. Such plot can be used as 3d generalization of step. See also surf, boxs, step, tiles. See tile sample, for sample code and picture.
-
-
-
-
MGL command: denszdat ['sch'='']
-
MGL command: densxdat ydat zdat ['sch'='']
-
The function draws density plot for surface specified parametrically {x[i,j], y[i,j], z[i,j]} at z equal to minimal z-axis value. If string sch have symbol `#` then grid lines are drawn. If string sch have symbol `.` then plot by dots is produced. See also surf, cont, contf, boxs, tile, dens[xyz]. See dens sample, for sample code and picture.
-
-
-
-
MGL command: contvdat zdat ['sch'='']
-
MGL command: contvdat xdat ydat zdat ['sch'='']
-
The function draws contour lines for surface specified parametrically {x[i,j], y[i,j], z[i,j]} at z=v[k], or at z equal to minimal z-axis value if sch contain symbol `_`. Contours are plotted for z[i,j]=v[k] where v[k] are values of data array v. If string sch have symbol `t` or `T` then contour labels v[k] will be drawn below (or above) the contours. See also dens, contf, contd, axial, cont[xyz]. See cont sample, for sample code and picture.
-
-
-
-
MGL command: contzdat ['sch'='']
-
MGL command: contxdat ydat zdat ['sch'='']
-
The same as previous with vector v of num-th elements equidistantly distributed in color range. Here num is equal to parameter value in options opt (default is 7). If string sch contain symbol `.` then only contours at levels with saddle points will be drawn.
-
-
-
-
MGL command: contfvdat zdat ['sch'='']
-
MGL command: contfvdat xdat ydat zdat ['sch'='']
-
The function draws solid (or filled) contour lines for surface specified parametrically {x[i,j], y[i,j], z[i,j]} at z=v[k], or at z equal to minimal z-axis value if sch contain symbol `_`. Contours are plotted for z[i,j]=v[k] where v[k] are values of data array v (must be v.nx>2). See also dens, cont, contd, contf[xyz]. See contf sample, for sample code and picture.
-
-
-
-
MGL command: contfzdat ['sch'='']
-
MGL command: contfxdat ydat zdat ['sch'='']
-
The same as previous with vector v of num-th elements equidistantly distributed in color range. Here num is equal to parameter value in options opt (default is 7).
-
-
-
-
MGL command: contdvdat zdat ['sch'='']
-
MGL command: contdvdat xdat ydat zdat ['sch'='']
-
The function draws solid (or filled) contour lines for surface specified parametrically {x[i,j], y[i,j], z[i,j]} at z=v[k] (or at z equal to minimal z-axis value if sch contain symbol `_`) with manual colors. Contours are plotted for z[i,j]=v[k] where v[k] are values of data array v (must be v.nx>2). String sch sets the contour colors: the color of k-th contour is determined by character sch[k%strlen(sch)]. See also dens, cont, contf. See contd sample, for sample code and picture.
-
-
-
-
MGL command: contdzdat ['sch'='']
-
MGL command: contdxdat ydat zdat ['sch'='']
-
The same as previous with vector v of num-th elements equidistantly distributed in color range. Here num is equal to parameter value in options opt (default is 7).
-
The function draws contour lines on surface specified parametrically {x[i,j], y[i,j], z[i,j]}. Contours are plotted for a[i,j]=v[k] where v[k] are values of data array v. If string sch have symbol `t` or `T` then contour labels v[k] will be drawn below (or above) the contours. If string sch have symbol `f` then solid contours will be drawn. See also cont, contf, surfc, cont[xyz].
-
-
-
MGL command: contpxdat ydat zdat adat ['sch'='']
-
The same as previous with vector v of num-th elements equidistantly distributed in color range. Here num is equal to parameter value in options opt (default is 7).
-
-
-
-
-
MGL command: contvvdat zdat ['sch'='']
-
MGL command: contvvdat xdat ydat zdat ['sch'='']
-
The function draws vertical cylinder (tube) at contour lines for surface specified parametrically {x[i,j], y[i,j], z[i,j]} at z=v[k], or at z equal to minimal z-axis value if sch contain symbol `_`. Contours are plotted for z[i,j]=v[k] where v[k] are values of data array v. See also cont, contf. See contv sample, for sample code and picture.
-
-
-
-
MGL command: contvzdat ['sch'='']
-
MGL command: contvxdat ydat zdat ['sch'='']
-
The same as previous with vector v of num-th elements equidistantly distributed in color range. Here num is equal to parameter value in options opt (default is 7).
-
-
-
-
MGL command: axialvdat zdat ['sch'='']
-
MGL command: axialvdat xdat ydat zdat ['sch'='']
-
The function draws surface which is result of contour plot rotation for surface specified parametrically {x[i,j], y[i,j], z[i,j]}. Contours are plotted for z[i,j]=v[k] where v[k] are values of data array v. If string sch have symbol `#` then wire plot is produced. If string sch have symbol `.` then plot by dots is produced. If string contain symbols `x` or `z` then rotation axis will be set to specified direction (default is `y`). See also cont, contf, torus, surf3. See axial sample, for sample code and picture.
-
-
-
-
MGL command: axialzdat ['sch'='']
-
MGL command: axialxdat ydat zdat ['sch'='']
-
The same as previous with vector v of num-th elements equidistantly distributed in color range. Here num is equal to parameter value in options opt (default is 3).
-
-
-
-
MGL command: grid2zdat ['sch'='']
-
MGL command: grid2xdat ydat zdat ['sch'='']
-
The function draws grid lines for density plot of surface specified parametrically {x[i,j], y[i,j], z[i,j]} at z equal to minimal z-axis value. See also dens, cont, contf, grid3, meshnum.
-
These functions perform plotting of 3D data. 3D means that data depend from 3 independent parameters like matrix f(x_i,y_j,z_k), i=1...n, j=1...m, k=1...l. By default (if absent) values of x, y, z are equidistantly distributed in axis range. The minor dimensions of arrays x, y, z, a should be equal x.nx=a.nx && y.nx=a.ny && z.nz=a.nz or x.nx=y.nx=z.nx=a.nx && x.ny=y.ny=z.ny=a.ny && x.nz=y.nz=z.nz=a.nz. Arrays x, y and z can be vectors (not matrices as a). String sch sets the color scheme (see Color scheme) for plot. String opt contain command options (see Command options).
-
-
-
MGL command: surf3adat val ['sch'='']
-
MGL command: surf3xdat ydat zdat adat val ['sch'='']
-
The function draws isosurface plot for 3d array specified parametrically a[i,j,k](x[i,j,k], y[i,j,k], z[i,j,k]) at a(x,y,z)=val. If string contain `#` then wire plot is produced. If string sch have symbol `.` then plot by dots is produced. Note, that there is possibility of incorrect plotting due to uncertainty of cross-section defining if there are two or more isosurface intersections inside one cell. See also cloud, dens3, surf3c, surf3a, axial. See surf3 sample, for sample code and picture.
-
-
-
-
MGL command: surf3adat ['sch'='']
-
MGL command: surf3xdat ydat zdat adat ['sch'='']
-
Draws num-th uniformly distributed in color range isosurfaces for 3d data. Here num is equal to parameter value in options opt (default is 3).
-
-
-
-
MGL command: cloudadat ['sch'='']
-
MGL command: cloudxdat ydat zdat adat ['sch'='']
-
The function draws cloud plot for 3d data specified parametrically a[i,j,k](x[i,j,k], y[i,j,k], z[i,j,k]). This plot is a set of cubes with color and transparency proportional to value of a. The resulting plot is like cloud - low value is transparent but higher ones are not. The number of plotting cells depend on meshnum. If string sch contain symbol `.` then lower quality plot will produced with much low memory usage. If string sch contain symbol `i` then transparency will be inversed, i.e. higher become transparent and lower become not transparent. See also surf3, meshnum. See cloud sample, for sample code and picture.
-
The function draws density plot for 3d data specified parametrically a[i,j,k](x[i,j,k], y[i,j,k], z[i,j,k]). Density is plotted at slice sVal in direction {`x`, `y`, `z`} if sch contain corresponding symbol (by default, `y` direction is used). If string stl have symbol `#` then grid lines are drawn. See also cont3, contf3, dens, grid3. See dens3 sample, for sample code and picture.
-
The function draws contour plot for 3d data specified parametrically a[i,j,k](x[i,j,k], y[i,j,k], z[i,j,k]). Contours are plotted for values specified in array v at slice sVal in direction {`x`, `y`, `z`} if sch contain corresponding symbol (by default, `y` direction is used). If string sch have symbol `#` then grid lines are drawn. If string sch have symbol `t` or `T` then contour labels will be drawn below (or above) the contours. See also dens3, contf3, cont, grid3. See cont3 sample, for sample code and picture.
-
The same as previous with vector v of num-th elements equidistantly distributed in color range. Here num is equal to parameter value in options opt (default is 7).
-
The function draws solid (or filled) contour plot for 3d data specified parametrically a[i,j,k](x[i,j,k], y[i,j,k], z[i,j,k]). Contours are plotted for values specified in array v at slice sVal in direction {`x`, `y`, `z`} if sch contain corresponding symbol (by default, `y` direction is used). If string sch have symbol `#` then grid lines are drawn. See also dens3, cont3, contf, grid3. See contf3 sample, for sample code and picture.
-
The same as previous with vector v of num-th elements equidistantly distributed in color range. Here num is equal to parameter value in options opt (default is 7).
-
The function draws grid for 3d data specified parametrically a[i,j,k](x[i,j,k], y[i,j,k], z[i,j,k]). Grid is plotted at slice sVal in direction {`x`, `y`, `z`} if sch contain corresponding symbol (by default, `y` direction is used). See also cont3, contf3, dens3, grid2, meshnum.
-
Draws the isosurface for 3d array a at constant values of a=val. This is special kind of plot for a specified in accompanied coordinates along curve tr with orts g1, g2 and with transverse scale r. Variable flag is bitwise: `0x1` - draw in accompanied (not laboratory) coordinates; `0x2` - draw projection to \rho-z plane; `0x4` - draw normalized in each slice field. The x-size of data arrays tr, g1, g2 must be nx>2. The y-size of data arrays tr, g1, g2 and z-size of the data array a must be equal. See also surf3.
-
These plotting functions draw two matrix simultaneously. There are 5 generally different types of data representations: surface or isosurface colored by other data (SurfC, Surf3C), surface or isosurface transpared by other data (SurfA, Surf3A), tiles with variable size (TileS), mapping diagram (Map), STFA diagram (STFA). By default (if absent) values of x, y, z are equidistantly distributed in axis range. The minor dimensions of arrays x, y, z, c should be equal. Arrays x, y (and z for Surf3C, Surf3A) can be vectors (not matrices as c). String sch sets the color scheme (see Color scheme) for plot. String opt contain command options (see Command options).
-
-
-
MGL command: surfczdat cdat ['sch'='']
-
MGL command: surfcxdat ydat zdat cdat ['sch'='']
-
The function draws surface specified parametrically {x[i,j], y[i,j], z[i,j]} and color it by matrix c[i,j]. If string sch have symbol `#` then grid lines are drawn. If string sch have symbol `.` then plot by dots is produced. All dimensions of arrays z and c must be equal. Surface is plotted for each z slice of the data. See also surf, surfa, surfca, beltc, surf3c. See surfc sample, for sample code and picture.
-
-
-
-
-
MGL command: beltczdat cdat ['sch'='']
-
MGL command: beltcxdat ydat zdat cdat ['sch'='']
-
The function draws belts for surface specified parametrically {x[i,j], y[i,j], z[i,j]} and color it by matrix c[i,j]. This plot can be used as 3d generalization of plot). If sch contain `x` then belts are drawn along x-direction else (by default) belts are drawn along y-direction. See also belt, surfc, meshnum.
-
-
-
-
-
MGL command: surf3cadat cdat val ['sch'='']
-
MGL command: surf3cxdat ydat zdat adat cdat val ['sch'='']
-
The function draws isosurface plot for 3d array specified parametrically a[i,j,k](x[i,j,k], y[i,j,k], z[i,j,k]) at a(x,y,z)=val. It is mostly the same as surf3 function but the color of isosurface depends on values of array c. If string sch contain `#` then wire plot is produced. If string sch have symbol `.` then plot by dots is produced. See also surf3, surfc, surf3a, surf3ca. See surf3c sample, for sample code and picture.
-
Draws num-th uniformly distributed in color range isosurfaces for 3d data. Here num is equal to parameter value in options opt (default is 3).
-
-
-
-
-
MGL command: surfazdat cdat ['sch'='']
-
MGL command: surfaxdat ydat zdat cdat ['sch'='']
-
The function draws surface specified parametrically {x[i,j], y[i,j], z[i,j]} and transparent it by matrix c[i,j]. If string sch have symbol `#` then grid lines are drawn. If string sch have symbol `.` then plot by dots is produced. All dimensions of arrays z and c must be equal. Surface is plotted for each z slice of the data. See also surf, surfc, surfca, surf3a. See surfa sample, for sample code and picture.
-
-
-
-
MGL command: surf3aadat cdat val ['sch'='']
-
MGL command: surf3axdat ydat zdat adat cdat val ['sch'='']
-
The function draws isosurface plot for 3d array specified parametrically a[i,j,k](x[i,j,k], y[i,j,k], z[i,j,k]) at a(x,y,z)=val. It is mostly the same as surf3 function but the transparency of isosurface depends on values of array c. If string sch contain `#` then wire plot is produced. If string sch have symbol `.` then plot by dots is produced. See also surf3, surfc, surf3a, surf3ca. See surf3a sample, for sample code and picture.
-
Draws num-th uniformly distributed in color range isosurfaces for 3d data. At this array c can be vector with values of transparency and num=c.nx. In opposite case num is equal to parameter value in options opt (default is 3).
-
The function draws surface specified parametrically {x[i,j], y[i,j], z[i,j]}, color it by matrix c[i,j] and transparent it by matrix a[i,j]. If string sch have symbol `#` then grid lines are drawn. If string sch have symbol `.` then plot by dots is produced. All dimensions of arrays z and c must be equal. Surface is plotted for each z slice of the data. Note, you can use map-like coloring if use `%` in color scheme. See also surf, surfc, surfa, surf3ca. See surfca sample, for sample code and picture.
-
-
-
-
MGL command: surf3caadat cdat bdat val ['sch'='']
-
MGL command: surf3caxdat ydat zdat adat cdat bdat val ['sch'='']
-
The function draws isosurface plot for 3d array specified parametrically a[i,j,k](x[i,j,k], y[i,j,k], z[i,j,k]) at a(x,y,z)=val. It is mostly the same as surf3 function but the color and the transparency of isosurface depends on values of array c and b correspondingly. If string sch contain `#` then wire plot is produced. If string sch have symbol `.` then plot by dots is produced. Note, you can use map-like coloring if use `%` in color scheme. See also surf3, surfca, surf3c, surf3a. See surf3ca sample, for sample code and picture.
-
Draws num-th uniformly distributed in color range isosurfaces for 3d data. Here parameter num is equal to parameter value in options opt (default is 3).
-
The function draws horizontal tiles for surface specified parametrically {x[i,j], y[i,j], z[i,j]} and color it by matrix c[i,j]. It is mostly the same as tile but the size of tiles is determined by r array. If string sch contain style `x` or `y` then tiles will be oriented perpendicular to x- or y-axis. This is some kind of “transparency” useful for exporting to EPS files. Tiles is plotted for each z slice of the data. See also surfa, tile. See tiles sample, for sample code and picture.
-
-
-
-
MGL command: mapudat vdat ['sch'='']
-
MGL command: mapxdat ydat udat vdat ['sch'='']
-
The function draws mapping plot for matrices {ax, ay } which parametrically depend on coordinates x, y. The initial position of the cell (point) is marked by color. Height is proportional to Jacobian(ax,ay). This plot is like Arnold diagram ??? If string sch contain symbol `.` then the color ball at matrix knots are drawn otherwise face is drawn. See Mapping visualization, for sample code and picture.
-
-
-
-
MGL command: stfare im dn ['sch'='']
-
MGL command: stfaxdat ydat re im dn ['sch'='']
-
Draws spectrogram of complex array re+i*im for Fourier size of dn points at plane z equal to minimal z-axis value. For example in 1D case, result is density plot of data res[i,j]=|\sum_d^dn exp(I*j*d)*(re[i*dn+d]+I*im[i*dn+d])|/dn with size {int(nx/dn), dn, ny}. At this array re, im parametrically depend on coordinates x, y. The size of re and im must be the same. The minor dimensions of arrays x, y, re should be equal. Arrays x, y can be vectors (not matrix as re). See stfa sample, for sample code and picture.
-
These functions perform plotting of 2D and 3D vector fields. There are 5 generally different types of vector fields representations: simple vector field (Vect), vectors along the curve (Traj), vector field by dew-drops (Dew), flow threads (Flow, FlowP), flow pipes (Pipe). By default (if absent) values of x, y, z are equidistantly distributed in axis range. The minor dimensions of arrays x, y, z, ax should be equal. The size of ax, ay and az must be equal. Arrays x, y, z can be vectors (not matrices as ax). String sch sets the color scheme (see Color scheme) for plot. String opt contain command options (see Command options).
-
The function draws vectors {ax, ay, az} along a curve {x, y, z}. The length of arrows are proportional to \sqrt{ax^2+ay^2+az^2}. String pen specifies the color (see Line styles). By default (pen="") color from palette is used (see Palette and colors). Option value set the vector length factor (if non-zero) or vector length to be proportional the distance between curve points (if value=0). The minor sizes of all arrays must be equal and large 2. The plots are drawn for each row if one of the data is the matrix. See also vect. See traj sample, for sample code and picture.
-
-
-
-
MGL command: vectudat vdat ['sch'='']
-
MGL command: vectxdat ydat udat vdat ['sch'='']
-
The function draws plane vector field plot for the field {ax, ay} depending parametrically on coordinates x, y at level z equal to minimal z-axis value. The length and color of arrows are proportional to \sqrt{ax^2+ay^2}. The number of arrows depend on meshnum. The appearance of the hachures (arrows) can be changed by symbols:
-
-
`f` for drawing arrows with fixed lengths,
-
`>`, `<` for drawing arrows to or from the cell point (default is centering),
-
`.` for drawing hachures with dots instead of arrows,
-
This is 3D version of the first functions. Here arrays ax, ay, az must be 3-ranged tensors with equal sizes and the length and color of arrows is proportional to \sqrt{ax^2+ay^2+az^2}.
-
The function draws 3D vector field plot for the field {ax, ay, az} depending parametrically on coordinates x, y, z. Vector field is drawn at slice sVal in direction {`x`, `y`, `z`} if sch contain corresponding symbol (by default, `y` direction is used). The length and color of arrows are proportional to \sqrt{ax^2+ay^2+az^2}. The number of arrows depend on meshnum. The appearance of the hachures (arrows) can be changed by symbols:
-
-
`f` for drawing arrows with fixed lengths,
-
`>`, `<` for drawing arrows to or from the cell point (default is centering),
-
`.` for drawing hachures with dots instead of arrows,
-
The function draws dew-drops for plane vector field {ax, ay} depending parametrically on coordinates x, y at level z equal to minimal z-axis value. Note that this is very expensive plot in memory usage and creation time! The color of drops is proportional to \sqrt{ax^2+ay^2}. The number of drops depend on meshnum. See also vect. See dew sample, for sample code and picture.
-
-
-
-
MGL command: flowudat vdat ['sch'='']
-
MGL command: flowxdat ydat udat vdat ['sch'='']
-
The function draws flow threads for the plane vector field {ax, ay} parametrically depending on coordinates x, y at level z equal to minimal z-axis value. Option value set the approximate number of threads (default is 5), or accuracy for stationary points (if style `.` is used) . String sch may contain:
-
-
color scheme - up-half (warm) corresponds to normal flow (like attractor), bottom-half (cold) corresponds to inverse flow (like source);
-
`#` for starting threads from edges only;
-
`.` for drawing separatrices only (flow threads to/from stationary points).
-
`*` for starting threads from a 2D array of points inside the data;
-
`v` for drawing arrows on the threads;
-
`x`, `z` for drawing tapes of normals in x-y and y-z planes correspondingly.
-
This is 3D version of the first functions. Here arrays ax, ay, az must be 3-ranged tensors with equal sizes and the color of line is proportional to \sqrt{ax^2+ay^2+az^2}.
-
The function draws flow threads for the 3D vector field {ax, ay, az} parametrically depending on coordinates x, y, z. Flow threads starts from given plane. Option value set the approximate number of threads (default is 5). String sch may contain:
-
-
color scheme - up-half (warm) corresponds to normal flow (like attractor), bottom-half (cold) corresponds to inverse flow (like source);
-
`x`, `z` for normal of starting plane (default is y-direction);
-
`v` for drawing arrows on the threads;
-
`t` for drawing tapes of normals in x-y and y-z planes.
-
The function draws gradient lines for scalar field phi[i,j] (or phi[i,j,k] in 3d case) specified parametrically {x[i,j,k], y[i,j,k], z[i,j,k]}. Number of lines is proportional to value option (default is 5). See also dens, cont, flow.
-
The function draws flow pipes for the plane vector field {ax, ay} parametrically depending on coordinates x, y at level z equal to minimal z-axis value. Number of pipes is proportional to value option (default is 5). If `#` symbol is specified then pipes start only from edges of axis range. The color of lines is proportional to \sqrt{ax^2+ay^2}. Warm color corresponds to normal flow (like attractor). Cold one corresponds to inverse flow (like source). Parameter r0 set the base pipe radius. If r0<0 or symbol `i` is specified then pipe radius is inverse proportional to amplitude. The vector field is plotted for each z slice of ax, ay. See also flow, vect. See pipe sample, for sample code and picture.
-
This is 3D version of the first functions. Here arrays ax, ay, az must be 3-ranged tensors with equal sizes and the color of line is proportional to \sqrt{ax^2+ay^2+az^2}.
-
These functions perform miscellaneous plotting. There is unstructured data points plots (Dots), surface reconstruction (Crust), surfaces on the triangular or quadrangular mesh (TriPlot, TriCont, QuadPlot), textual formula plotting (Plots by formula), data plots at edges (Dens[XYZ], Cont[XYZ], ContF[XYZ]). Each type of plotting has similar interface. There are 2 kind of versions which handle the arrays of data and coordinates or only single data array. Parameters of color scheme are specified by the string argument. See Color scheme.
-
-
-
MGL command: densxdat ['sch'='' sval=nan]
-
MGL command: densydat ['sch'='' sval=nan]
-
MGL command: denszdat ['sch'='' sval=nan]
-
These plotting functions draw density plot in x, y, or z plain. If a is a tensor (3-dimensional data) then interpolation to a given sVal is performed. These functions are useful for creating projections of the 3D data array to the bounding box. See also ContXYZ, ContFXYZ, dens, Data manipulation. See dens_xyz sample, for sample code and picture.
-
-
-
-
MGL command: contxdat ['sch'='' sval=nan]
-
MGL command: contydat ['sch'='' sval=nan]
-
MGL command: contzdat ['sch'='' sval=nan]
-
These plotting functions draw contour lines in x, y, or z plain. If a is a tensor (3-dimensional data) then interpolation to a given sVal is performed. These functions are useful for creating projections of the 3D data array to the bounding box. Option value set the number of contours. See also ContFXYZ, DensXYZ, cont, Data manipulation. See cont_xyz sample, for sample code and picture.
-
-
-
-
-
MGL command: contfxdat ['sch'='' sval=nan]
-
MGL command: contfydat ['sch'='' sval=nan]
-
MGL command: contfzdat ['sch'='' sval=nan]
-
These plotting functions draw solid contours in x, y, or z plain. If a is a tensor (3-dimensional data) then interpolation to a given sVal is performed. These functions are useful for creating projections of the 3D data array to the bounding box. Option value set the number of contours. See also ContFXYZ, DensXYZ, cont, Data manipulation. See contf_xyz sample, for sample code and picture.
-
-
-
-
-
MGL command: fplot'y(x)' ['pen'='']
-
Draws command function `y(x)` at plane z equal to minimal z-axis value, where `x` variable is changed in xrange. You do not need to create the data arrays to plot it. Option value set initial number of points. See also plot.
-
-
-
-
MGL command: fplot'x(t)' 'y(t)' 'z(t)' ['pen'='']
-
Draws command parametrical curve {`x(t)`, `y(t)`, `z(t)`} where `t` variable is changed in range [0, 1]. You do not need to create the data arrays to plot it. Option value set number of points. See also plot.
-
-
-
-
MGL command: fsurf'z(x,y)' ['sch'='']
-
Draws command surface for function `z(x,y)` where `x`, `y` variable are changed in xrange, yrange. You do not need to create the data arrays to plot it. Option value set number of points. See also surf.
-
Draws command parametrical surface {`x(u,v)`, `y(u,v)`, `z(u,v)`} where `u`, `v` variable are changed in range [0, 1]. You do not need to create the data arrays to plot it. Option value set number of points. See also surf.
-
The function draws the surface of triangles. Triangle vertexes are set by indexes id of data points {x[i], y[i], z[i]}. String sch sets the color scheme. If string contain `#` then wire plot is produced. First dimensions of id must be 3 or greater. Arrays x, y, z must have equal sizes. Parameter c set the colors of triangles (if id.ny=c.nx) or colors of vertexes (if x.nx=c.nx). See also dots, crust, quadplot, triangulation. See triplot sample, for sample code and picture.
-
The function draws contour lines for surface of triangles at z=v[k] (or at z equal to minimal z-axis value if sch contain symbol `_`). Triangle vertexes are set by indexes id of data points {x[i], y[i], z[i]}. Contours are plotted for z[i,j]=v[k] where v[k] are values of data array v. If v is absent then arrays of option value elements equidistantly distributed in color range is used. String sch sets the color scheme. Array c (if specified) is used for contour coloring. First dimensions of id must be 3 or greater. Arrays x, y, z must have equal sizes. Parameter c set the colors of triangles (if id.ny=c.nx) or colors of vertexes (if x.nx=c.nx). See also triplot, cont, triangulation.
-
The function draws the surface of quadrangles. Quadrangles vertexes are set by indexes id of data points {x[i], y[i], z[i]}. String sch sets the color scheme. If string contain `#` then wire plot is produced. First dimensions of id must be 4 or greater. Arrays x, y, z must have equal sizes. Parameter c set the colors of quadrangles (if id.ny=c.nx) or colors of vertexes (if x.nx=c.nx). See also triplot. See triplot sample, for sample code and picture.
-
-
-
-
MGL command: dotsxdat ydat zdat ['sch'='']
-
MGL command: dotsxdat ydat zdat adat ['sch'='']
-
The function draws the arbitrary placed points {x[i], y[i], z[i]}. String sch sets the color scheme and kind of marks. If arrays c, a are specified then they define colors and transparencies of dots. You can use tens plot with style ` .` to draw non-transparent dots with specified colors. Arrays x, y, z, a must have equal sizes. See also crust, tens, mark, plot. See dots sample, for sample code and picture.
-
-
-
-
MGL command: crustxdat ydat zdat ['sch'='']
-
The function reconstruct and draws the surface for arbitrary placed points {x[i], y[i], z[i]}. String sch sets the color scheme. If string contain `#` then wire plot is produced. Arrays x, y, z must have equal sizes. See also dots, triplot.
These functions fit data to formula. Fitting goal is to find formula parameters for the best fit the data points, i.e. to minimize the sum \sum_i (f(x_i, y_i, z_i) - a_i)^2/s_i^2. At this, approximation function `f` can depend only on one argument `x` (1D case), on two arguments `x,y` (2D case) and on three arguments `x,y,z` (3D case). The function `f` also may depend on parameters. Normally the list of fitted parameters is specified by var string (like, `abcd`). Usually user should supply initial values for fitted parameters by ini variable. But if he/she don`t supply it then the zeros are used. Parameter print=true switch on printing the found coefficients to Message (see Error handling).
-
-
Functions Fit() and FitS() do not draw the obtained data themselves. They fill the data fit by formula `f` with found coefficients and return it. At this, the `x,y,z` coordinates are equidistantly distributed in the axis range. Number of points in fit is defined by option value (default is mglFitPnts=100). Note, that this functions use GSL library and do something only if MathGL was compiled with GSL support. See Nonlinear fitting hints, for sample code and picture.
-
Fit data along x-, y- and z-directions for array specified parametrically a[i,j,k](x[i,j,k], y[i,j,k], z[i,j,k]) with weight factor 1.
-
-
-
-
-
-
MGL command: putsfitx y ['pre'='' 'fnt'='' size=-1]
-
Print last fitted formula with found coefficients (as numbers) at position p0. The string prefix will be printed before formula. All other parameters are the same as in Text printing.
-
These functions make distribution (histogram) of data. They do not draw the obtained data themselves. These functions can be useful if user have data defined for random points (for example, after PIC simulation) and he want to produce a plot which require regular data (defined on grid(s)). The range for grids is always selected as axis range. Arrays x, y, z define the positions (coordinates) of random points. Array a define the data value. Number of points in output array res is defined by option value (default is mglFitPnts=100).
-
-
-
-
-
MGL command: filldat 'eq'
-
MGL command: filldat 'eq' vdat
-
MGL command: filldat 'eq' vdat wdat
-
Fills the value of array `u` according to the formula in string eq. Formula is an arbitrary expression depending on variables `x`, `y`, `z`, `u`, `v`, `w`. Coordinates `x`, `y`, `z` are supposed to be normalized in axis range. Variable `u` is the original value of the array. Variables `v` and `w` are values of arrays v, w which can be NULL (i.e. can be omitted).
-
-
-
-
MGL command: datagriddat xdat ydat zdat
-
Fills the value of array `u` according to the linear interpolation of triangulated surface, found for arbitrary placed points `x`, `y`, `z`. Interpolation is done at points equidistantly distributed in axis range. NAN value is used for grid points placed outside of triangulated surface. See Making regular data, for sample code and picture.
-
-
-
-
MGL command: refilldat xdat vdat [sl=-1]
-
MGL command: refilldat xdat ydat vdat [sl=-1]
-
MGL command: refilldat xdat ydat zdat vdat
-
Fills by interpolated values of array v at the point {x, y, z}={X[i], Y[j], Z[k]} (or {x, y, z}={X[i,j,k], Y[i,j,k], Z[i,j,k]} if x, y, z are not 1d arrays), where X,Y,Z are equidistantly distributed in axis range and have the same sizes as array dat. If parameter sl is 0 or positive then changes will be applied only for slice sl.
-
Solves equation du/dz = i*k0*ham(p,q,x,y,z,|u|)[u], where p=-i/k0*d/dx, q=-i/k0*d/dy are pseudo-differential operators. Parameters ini_re, ini_im specify real and imaginary part of initial field distribution. Coordinates `x`, `y`, `z` are supposed to be normalized in axis range. Note, that really this ranges are increased by factor 3/2 for purpose of reducing reflection from boundaries. Parameter dz set the step along evolutionary coordinate z. At this moment, simplified form of function ham is supported - all “mixed” terms (like `x*p`->x*d/dx) are excluded. For example, in 2D case this function is effectively ham = f(p,z) + g(x,z,u). However commutable combinations (like `x*q`->x*d/dy) are allowed. Here variable `u` is used for field amplitude |u|. This allow one solve nonlinear problems - for example, for nonlinear Shrodinger equation you may set ham="p^2 + q^2 - u^2". You may specify imaginary part for wave absorption, like ham = "p^2 + i*x*(x>0)", but only if dependence on variable `i` is linear (i.e. ham = hre+i*him). See PDE solving hints, for sample code and picture.
-
This chapter describe commands for allocation, resizing, loading and saving, modifying of data arrays. Also it can numerically differentiate and integrate data, interpolate, fill data by formula and so on. Class supports data with dimensions up to 3 (like function of 3 variables - x,y,z). Data arrays are denoted by Small Caps (like DAT) if it can be (re-)created by MGL commands.
-
Default constructor. Allocates the memory for data array and initializes it by zero. If string eq is specified then data will be filled by corresponding formula as in fill.
-
-
-
-
MGL command: copyDAT dat2 ['eq'='']
-
MGL command: copyDAT val
-
Copy constructor. Allocates the memory for data array and copy values from other array. At this, if parameter eq or val is specified then the data will be modified by corresponding formula similarly to fill.
-
-
-
-
MGL command: copyREDAT IMDAT dat2 ['eq'='']
-
Allocates the memory for data array and copy real and imaginary values from complex array dat2.
-
-
-
-
MGL command: copy'name'
-
Allocates the memory for data array and copy values from other array specified by its name, which can be "invalid" for MGL names (like one read from HDF5 files).
-
-
-
-
-
MGL command: readDAT 'fname'
-
Reads data from tab-separated text file with auto determining sizes of the data.
-
Creates or recreates the array with specified size and fills it by zero. This function does nothing if one of parameters mx, my, mz is zero or negative.
-
-
-
-
MGL command: rearrangedat mx [my=0 mz=0]
-
Rearrange dimensions without changing data array so that resulting sizes should be mx*my*mz < nx*ny*nz. If some of parameter my or mz are zero then it will be selected to optimal fill of data array. For example, if my=0 then it will be change to my=nx*ny*nz/mx and mz=1.
-
-
-
-
MGL command: transposedat ['dim'='yxz']
-
Transposes (shift order of) dimensions of the data. New order of dimensions is specified in string dim. This function can be useful also after reading of one-dimensional data.
-
-
-
-
MGL command: extenddat n1 [n2=0]
-
Increase the dimensions of the data by inserting new (|n1|+1)-th slices after (for n1>0) or before (for n1<0) of existed one. It is possible to insert 2 dimensions simultaneously for 1d data by using parameter n2. Data to new slices is copy from existed one. For example, for n1>0 new array will be
-a_ij^new = a_i^old where j=0...n1. Correspondingly, for n1<0 new array will be a_ij^new = a_j^old where i=0...|n1|.
-
-
-
-
MGL command: squeezedat rx [ry=1 rz=1 sm=off]
-
Reduces the data size by excluding data elements which indexes are not divisible by rx, ry, rz correspondingly. Parameter smooth set to use smoothing
-(i.e. out[i]=\sum_{j=i,i+r} a[j]/r) or not (i.e. out[i]=a[j*r]).
-
-
-
-
MGL command: cropdat n1 n2 'dir'
-
Cuts off edges of the data i<n1 and i>n2 if n2>0 or i>n[xyz]-n2 if n2<=0 along direction dir.
-
-
-
-
MGL command: cropdat 'how'
-
Cuts off far edge of the data to be more optimal for fast Fourier transform. The resulting size will be the closest value of 2^n*3^m*5^l to the original one. The string how may contain: `x`, `y`, `z` for directions, and `2`, `3`, `5` for using corresponding bases.
-
-
-
-
MGL command: insertdat 'dir' [pos=off num=0]
-
Insert num slices along dir-direction at position pos and fill it by zeros.
-
-
-
-
MGL command: deletedat 'dir' [pos=off num=0]
-
Delete num slices along dir-direction at position pos.
-
-
-
-
MGL command: deletedat
-
MGL command: delete'name'
-
Deletes the whole data array.
-
-
-
-
MGL command: sortdat idx [idy=-1]
-
Sort data rows (or slices in 3D case) by values of specified column idx (or cell {idx,idy} for 3D case). Note, this function is not thread safe!
-
-
-
-
MGL command: cleandat idx
-
Delete rows which values are equal to next row for given column idx.
-
-
-
-
MGL command: joindat vdat [v2dat ...]
-
Join data cells from vdat to dat. At this, function increase dat sizes according following: z-size for data arrays arrays with equal x-,y-sizes; or y-size for data arrays with equal x-sizes; or x-size otherwise.
-
Creates new variable with name dat and fills it by numeric values of command arguments v1 .... Command can create one-dimensional and two-dimensional arrays with arbitrary values. For creating 2d array the user should use delimiter `|` which means that the following values lie in next row. Array sizes are [maximal of row sizes * number of rows]. For example, command list 1 | 2 3 creates the array [1 0; 2 3]. Note, that the maximal number of arguments is 1000.
-
-
-
MGL command: listDAT d1 ...
-
Creates new variable with name dat and fills it by data values of arrays of command arguments d1 .... Command can create two-dimensional or three-dimensional (if arrays in arguments are 2d arrays) arrays with arbitrary values. Minor dimensions of all arrays in arguments should be equal to dimensions of first array d1. In the opposite case the argument will be ignored. Note, that the maximal number of arguments is 1000.
-
-
-
-
-
MGL command: varDAT num v1 [v2=nan]
-
Creates new variable with name dat for one-dimensional array of size num. Array elements are equidistantly distributed in range [v1, v2]. If v2=nan then v2=v1 is used.
-
-
-
-
MGL command: filldat v1 v2 ['dir'='x']
-
Equidistantly fills the data values to range [v1, v2] in direction dir={`x`,`y`,`z`}.
-
-
-
-
MGL command: filldat 'eq' [vdat wdat]
-
Fills the value of array according to the formula in string eq. Formula is an arbitrary expression depending on variables `x`, `y`, `z`, `u`, `v`, `w`. Coordinates `x`, `y`, `z` are supposed to be normalized in axis range of canvas gr (in difference from Modify functions). Variable `u` is the original value of the array. Variables `v` and `w` are values of vdat, wdat which can be NULL (i.e. can be omitted).
-
-
-
-
MGL command: modifydat 'eq' [dim=0]
-
MGL command: modifydat 'eq' vdat [wdat]
-
The same as previous ones but coordinates `x`, `y`, `z` are supposed to be normalized in range [0,1]. If dim>0 is specified then modification will be fulfilled only for slices >=dim.
-
-
-
-
MGL command: fillsampledat 'how'
-
Fills data by `x` or `k` samples for Hankel (`h`) or Fourier (`f`) transform.
-
-
-
-
-
MGL command: datagriddat xdat ydat zdat
-
Fills the value of array according to the linear interpolation of triangulated surface assuming x-,y-coordinates equidistantly distributed in axis range (or in range [x1,x2]*[y1,y2]). Triangulated surface is found for arbitrary placed points `x`, `y`, `z`. NAN value is used for grid points placed outside of triangulated surface. See Making regular data, for sample code and picture.
-
-
-
-
-
MGL command: putdat val [i=all j=all k=all]
-
Sets value(s) of array a[i, j, k] = val. Negative indexes i, j, k=-1 set the value val to whole range in corresponding direction(s). For example, Put(val,-1,0,-1); sets a[i,0,j]=val for i=0...(nx-1), j=0...(nz-1).
-
-
-
-
MGL command: putdat vdat [i=all j=all k=all]
-
Copies value(s) from array v to the range of original array. Negative indexes i, j, k=-1 set the range in corresponding direction(s). At this minor dimensions of array v should be large than corresponding dimensions of this array. For example, Put(v,-1,0,-1); sets a[i,0,j]=v.ny>nz ? v[i,j] : v[i], where i=0...(nx-1), j=0...(nz-1) and condition v.nx>=nx is true.
-
-
-
-
MGL command: refilldat xdat vdat [sl=-1]
-
MGL command: refilldat xdat ydat vdat [sl=-1]
-
MGL command: refilldat xdat ydat zdat vdat
-
Fills by interpolated values of array v at the point {x, y, z}={X[i], Y[j], Z[k]} (or {x, y, z}={X[i,j,k], Y[i,j,k], Z[i,j,k]} if x, y, z are not 1d arrays), where X,Y,Z are equidistantly distributed in range [x1,x2]*[y1,y2]*[z1,z2] and have the same sizes as this array. If parameter sl is 0 or positive then changes will be applied only for slice sl.
-
-
-
-
MGL command: gsplinedat xdat vdat [sl=-1]
-
Fills by global cubic spline values of array v at the point x=X[i], where X are equidistantly distributed in range [x1,x2] and have the same sizes as this array. If parameter sl is 0 or positive then changes will be applied only for slice sl.
-
-
-
-
MGL command: idsetdat 'ids'
-
Sets the symbol ids for data columns. The string should contain one symbol `a`...`z` per column. These ids are used in column.
-
Join data arrays from several text files. The file names are determined by function call sprintf(fname,templ,val);, where val changes from from to to with step step. The data load one-by-one in the same slice if as_slice=false or as slice-by-slice if as_slice=true.
-
-
-
-
MGL command: readallDAT 'templ' [slice=off]
-
Join data arrays from several text files which filenames satisfied the template templ (for example, templ="t_*.dat"). The data load one-by-one in the same slice if as_slice=false or as slice-by-slice if as_slice=true.
-
-
-
-
MGL command: scanfileDAT 'fname' 'templ'
-
Read file fname line-by-line and scan each line for numbers according the template templ. The numbers denoted as `%g` in the template. See Saving and scanning file, for sample code and picture.
-
-
-
-
MGL command: savedat 'fname'
-
Saves the whole data array (for ns=-1) or only ns-th slice to the text file fname.
-
-
-
-
MGL command: save'str' 'fname' ['mode'='a']
-
Saves the string str to the text file fname. For parameter mode=`a` will append string to the file (default); for mode=`w` will overwrite the file. See Saving and scanning file, for sample code and picture.
-
-
-
-
-
MGL command: readhdfDAT 'fname' 'dname'
-
Reads data array named dname from HDF5 or HDF4 file. This function does nothing if HDF5|HDF4 was disabled during library compilation.
-
Saves data array named dname to HDF5 file. This function does nothing if HDF5 was disabled during library compilation.
-
-
-
-
MGL command: datas'fname'
-
Put data names from HDF5 file fname into buf as `\t` separated fields. In MGL version the list of data names will be printed as message. This function does nothing if HDF5 was disabled during library compilation.
-
-
-
-
MGL command: openhdf'fname'
-
Reads all data array from HDF5 file fname and create MGL variables with names of data names in HDF file. Complex variables will be created if data name starts with `!`.
-
-
-
-
-
-
MGL command: importDAT 'fname' 'sch' [v1=0 v2=1]
-
Reads data from bitmap file (now support only PNG format). The RGB values of bitmap pixels are transformed to mreal values in range [v1, v2] using color scheme scheme (see Color scheme).
-
-
-
-
MGL command: exportdat 'fname' 'sch' [v1=0 v2=0]
-
Saves data matrix (or ns-th slice for 3d data) to bitmap file (now support only PNG format). The data values are transformed from range [v1, v2] to RGB pixels of bitmap using color scheme scheme (see Color scheme). If v1>=v2 then the values of v1, v2 are automatically determined as minimal and maximal value of the data array.
-
Extracts sub-array data from the original data array keeping fixed positive index. For example SubData(-1,2) extracts 3d row (indexes are zero based), SubData(4,-1) extracts 5th column, SubData(-1,-1,3) extracts 4th slice and so on. If argument(s) are non-integer then linear interpolation between slices is used. In MGL version this command usually is used as inline one dat(xx,yy,zz). Function return NULL or create empty data if data cannot be created for given arguments.
-
-
-
-
MGL command: subdataRES dat xdat [ydat zdat]
-
Extracts sub-array data from the original data array for indexes specified by arrays xx, yy, zz (indirect access). This function work like previous one for 1D arguments or numbers, and resulting array dimensions are equal dimensions of 1D arrays for corresponding direction. For 2D and 3D arrays in arguments, the resulting array have the same dimensions as input arrays. The dimensions of all argument must be the same (or to be scalar 1*1*1) if they are 2D or 3D arrays. In MGL version this command usually is used as inline one dat(xx,yy,zz). Function return NULL or create empty data if data cannot be created for given arguments. In C function some of xx, yy, zz can be NULL.
-
-
-
-
MGL command: columnRES dat 'eq'
-
Get column (or slice) of the data filled by formula eq on column ids. For example, Column("n*w^2/exp(t)");. The column ids must be defined first by idset function or read from files. In MGL version this command usually is used as inline one dat('eq'). Function return NULL or create empty data if data cannot be created for given arguments.
-
-
-
-
MGL command: resizeRES dat mx [my=1 mz=1]
-
Resizes the data to new size mx, my, mz from box (part) [x1,x2] x [y1,y2] x [z1,z2] of original array. Initially x,y,z coordinates are supposed to be in [0,1]. If one of sizes mx, my or mz is 0 then initial size is used. Function return NULL or create empty data if data cannot be created for given arguments.
-
-
-
-
MGL command: evaluateRES dat idat [norm=on]
-
MGL command: evaluateRES dat idat jdat [norm=on]
-
MGL command: evaluateRES dat idat jdat kdat [norm=on]
-
Gets array which values is result of interpolation of original array for coordinates from other arrays. All dimensions must be the same for data idat, jdat, kdat. Coordinates from idat, jdat, kdat are supposed to be normalized in range [0,1] (if norm=true) or in ranges [0,nx], [0,ny], [0,nz] correspondingly. Function return NULL or create empty data if data cannot be created for given arguments.
-
-
-
-
MGL command: sectionRES dat ids ['dir'='y' val=nan]
-
MGL command: sectionRES dat id ['dir'='y' val=nan]
-
Gets array which is id-th section (range of slices separated by value val) of original array dat. For id<0 the reverse order is used (i.e. -1 give last section). If several ids are provided then output array will be result of sequential joining of sections.
-
-
-
-
-
MGL command: solveRES dat val 'dir' [norm=on]
-
MGL command: solveRES dat val 'dir' idat [norm=on]
-
Gets array which values is indexes (roots) along given direction dir, where interpolated values of data dat are equal to val. Output data will have the sizes of dat in directions transverse to dir. If data idat is provided then its values are used as starting points. This allows to find several branches by consequentive calls. Indexes are supposed to be normalized in range [0,1] (if norm=true) or in ranges [0,nx], [0,ny], [0,nz] correspondingly. Function return NULL or create empty data if data cannot be created for given arguments. See Solve sample, for sample code and picture.
-
-
-
-
MGL command: rootsRES 'func' ini ['var'='x']
-
MGL command: rootsRES 'func' ini ['var'='x']
-
Find roots of equation `func`=0 for variable var with initial guess ini. Secant method is used for root finding. Function return NULL or create empty data if data cannot be created for given arguments.
-
-
-
-
MGL command: rootsRES 'funcs' 'vars' ini
-
Find roots of system of equations `funcs`=0 for variables vars with initial guesses ini. Secant method is used for root finding. Function return NULL or create empty data if data cannot be created for given arguments.
-
-
-
-
MGL command: detectRES dat lvl dj [di=0 minlen=0]
-
Get curves {x,y}, separated by NAN values, for local maximal values of array dat as function of x-coordinate. Noises below lvl amplitude are ignored. Parameter dj (in range [0,ny]) set the "attraction" y-distance of points to the curve. Similarly, di continue curve in x-direction through gaps smaller than di points. Curves with minimal length smaller than minlen will be ignored.
-
-
-
-
MGL command: histRES dat num v1 v2 [nsub=0]
-
MGL command: histRES dat wdat num v1 v2 [nsub=0]
-
Creates n-th points distribution of the data values in range [v1, v2]. Array w specifies weights of the data elements (by default is 1). Parameter nsub define the number of additional interpolated points (for smoothness of histogram). Function return NULL or create empty data if data cannot be created for given arguments. See also Data manipulation
-
-
-
-
MGL command: momentumRES dat 'how' ['dir'='z']
-
Gets momentum (1d-array) of the data along direction dir. String how contain kind of momentum. The momentum is defined like as
-res_k = \sum_ij how(x_i,y_j,z_k) a_ij/ \sum_ij a_ij
-if dir=`z` and so on. Coordinates `x`, `y`, `z` are data indexes normalized in range [0,1]. Function return NULL or create empty data if data cannot be created for given arguments.
-
-
-
-
MGL command: sumRES dat 'dir'
-
Gets array which is the result of summation in given direction or direction(s). Function return NULL or create empty data if data cannot be created for given arguments.
-
-
-
-
MGL command: maxRES dat 'dir'
-
Gets array which is the maximal data values in given direction or direction(s). Function return NULL or create empty data if data cannot be created for given arguments.
-
-
-
-
MGL command: minRES dat 'dir'
-
Gets array which is the maximal data values in given direction or direction(s). Function return NULL or create empty data if data cannot be created for given arguments.
-
-
-
-
MGL command: combineRES adat bdat
-
Returns direct multiplication of arrays (like, res[i,j] = this[i]*a[j] and so on). Function return NULL or create empty data if data cannot be created for given arguments.
-
-
-
-
MGL command: traceRES dat
-
Gets array of diagonal elements a[i,i] (for 2D case) or a[i,i,i] (for 3D case) where i=0...nx-1. Function return copy of itself for 1D case. Data array must have dimensions ny,nz >= nx or ny,nz = 1. Function return NULL or create empty data if data cannot be created for given arguments.
-
-
-
-
MGL command: correlRES adat bdat 'dir'
-
Find correlation between data a (or this in C++) and b along directions dir. Fourier transform is used to find the correlation. So, you may want to use functions swap or norm before plotting it. Function return NULL or create empty data if data cannot be created for given arguments.
-
-
-
-
-
MGL command: pulseRES dat 'dir'
-
Find pulse properties along direction dir: pulse maximum (in column 0) and its position (in column 1), pulse width near maximum (in column 3) and by half height (in column 2), energy in first pulse (in column 4). NAN values are used for widths if maximum is located near the edges. Note, that there is uncertainty for complex data. Usually one should use square of absolute value (i.e. |dat[i]|^2) for them. So, MathGL don`t provide this function for complex data arrays. However, C function will work even in this case but use absolute value (i.e. |dat[i]|). Function return NULL or create empty data if data cannot be created for given arguments. See also max, min, momentum, sum. See Pulse properties, for sample code and picture.
-
These functions change the data in some direction like differentiations, integrations and so on. The direction in which the change will applied is specified by the string parameter, which may contain `x`, `y` or `z` characters for 1-st, 2-nd and 3-d dimension correspondingly.
-
-
-
MGL command: cumsumdat 'dir'
-
Cumulative summation of the data in given direction or directions.
-
-
-
-
MGL command: integratedat 'dir'
-
Integrates (like cumulative summation) the data in given direction or directions.
-
-
-
-
MGL command: diffdat 'dir'
-
Differentiates the data in given direction or directions.
-
-
-
-
MGL command: diffdat xdat ydat [zdat]
-
Differentiates the data specified parametrically in direction x with y, z=constant. Parametrical differentiation uses the formula (for 2D case): da/dx = (a_j*y_i-a_i*y_j)/(x_j*y_i-x_i*y_j) where a_i=da/di, a_j=da/dj denotes usual differentiation along 1st and 2nd dimensions. The similar formula is used for 3D case. Note, that you may change the order of arguments - for example, if you have 2D data a(i,j) which depend on coordinates {x(i,j), y(i,j)} then usual derivative along `x` will be Diff(x,y); and usual derivative along `y` will be Diff(y,x);.
-
-
-
-
MGL command: diff2dat 'dir'
-
Double-differentiates (like Laplace operator) the data in given direction.
-
Apply wavelet transform of the data in given direction or directions. Parameter dir set the kind of wavelet transform:
-`d` for daubechies, `D` for centered daubechies, `h` for haar, `H` for centered haar, `b` for bspline, `B` for centered bspline. If string dir contain symbol `i` then inverse wavelet transform is applied. Parameter k set the size of wavelet transform.
-
-
-
-
MGL command: swapdat 'dir'
-
Swaps the left and right part of the data in given direction (useful for Fourier spectrum).
-
-
-
-
MGL command: rolldat 'dir' num
-
Rolls the data along direction dir. Resulting array will be out[i] = ini[(i+num)%nx] if dir='x'.
-
-
-
-
MGL command: mirrordat 'dir'
-
Mirror the left-to-right part of the data in given direction. Looks like change the value index i->n-i. Note, that the similar effect in graphics you can reach by using options (see Command options), for example, surf dat; xrange 1 -1.
-
-
-
-
MGL command: sewdat ['dir'='xyz' da=2*pi]
-
Remove value steps (like phase jumps after inverse trigonometric functions) with period da in given direction.
-
-
-
-
MGL command: smoothdata ['dir'='xyz']
-
Smooths the data on specified direction or directions. String dirs specifies the dimensions which will be smoothed. It may contain characters:
-
-
`xyz` for smoothing along x-,y-,z-directions correspondingly,
-
`0` does nothing,
-
`3` for linear averaging over 3 points,
-
`5` for linear averaging over 5 points,
-
`d1`...`d9` for linear averaging over (2*N+1)-th points.
-
-
By default quadratic averaging over 5 points is used.
-
-
-
-
MGL command: envelopdat ['dir'='x']
-
Find envelop for data values along direction dir.
-
-
-
-
MGL command: diffractdat 'how' q
-
Calculates one step of diffraction by finite-difference method with parameter q=\delta t/\delta x^2 using method with 3-d order of accuracy. Parameter how may contain:
-
-
`xyz` for calculations along x-,y-,z-directions correspondingly;
-
`r` for using axial symmetric Laplace operator for x-direction;
-
`0` for zero boundary conditions;
-
`1` for constant boundary conditions;
-
`2` for linear boundary conditions;
-
`3` for parabolic boundary conditions;
-
`4` for exponential boundary conditions;
-
`5` for gaussian boundary conditions.
-
-
-
-
-
MGL command: normdat v1 v2 [sym=off dim=0]
-
Normalizes the data to range [v1,v2]. If flag sym=true then symmetrical interval [-max(|v1|,|v2|), max(|v1|,|v2|)] is used. Modification will be applied only for slices >=dim.
-
Normalizes data slice-by-slice along direction dir the data in slices to range [v1,v2]. If flag sym=true then symmetrical interval [-max(|v1|,|v2|), max(|v1|,|v2|)] is used. If keep is set then maximal value of k-th slice will be limited by
-\sqrt{\sum a_ij(k)/\sum a_ij(0)}.
-
-
-
-
MGL command: limitdat val
-
Limits the data values to be inside the range [-val,val], keeping the original sign of the value (phase for complex numbers). This is equivalent to operation a[i] *= abs(a[i])<val?1.:val/abs(a[i]);.
-
-
-
-
MGL command: coildat v1 v2 [sep=on]
-
Project the periodical data to range [v1,v2] (like mod() function). Separate branches by NAN if sep=true.
-
-
-
-
-
MGL command: dilatedat [val=1 step=1]
-
Return dilated by step cells array of 0 or 1 for data values larger val.
-
-
-
MGL command: erodedat [val=1 step=1]
-
Return eroded by step cells array of 0 or 1 for data values larger val.
There are a set of functions for obtaining data properties in MGL language. However most of them can be found using "suffixes". Suffix can get some numerical value of the data array (like its size, maximal or minimal value, the sum of elements and so on) as number. Later it can be used as usual number in command arguments. The suffixes start from point `.` right after (without spaces) variable name or its sub-array. For example, a.nx give the x-size of data a, b(1).max give maximal value of second row of variable b, (c(:,0)^2).sum give the sum of squares of elements in the first column of c and so on.
-
-
-
-
-
MGL command: infodat
-
Gets or prints to file fp or as message (in MGL) information about the data (sizes, maximum/minimum, momentums and so on).
-
-
-
-
MGL command: info'txt'
-
Prints string txt as message.
-
-
-
-
MGL command: infoval
-
Prints value of number val as message.
-
-
-
-
MGL command: printdat
-
MGL command: print'txt'
-
MGL command: printval
-
The same as info but immediately print to stdout.
-
-
-
-
MGL command: echodat
-
Prints all values of the data array dat as message.
-
-
-
-
MGL command: progressval max
-
Display progress of something as filled horizontal bar with relative length val/max. Note, it work now only in console and in FLTK-based applications, including mgllab and mglview.
-
-
-
-
-
-
-
-
MGL suffix: (dat).nx
-
MGL suffix: (dat).ny
-
MGL suffix: (dat).nz
-
Gets the x-, y-, z-size of the data.
-
-
-
-
-
-
-
MGL suffix: (dat).max
-
Gets maximal value of the data.
-
-
-
-
-
MGL suffix: (dat).min
-
Gets minimal value of the data.
-
-
-
-
-
MGL suffix: (dat).mx
-
MGL suffix: (dat).my
-
MGL suffix: (dat).mz
-
Gets approximated (interpolated) position of maximum to variables x, y, z and returns the maximal value.
-
-
-
-
-
MGL suffix: (dat).mxf
-
MGL suffix: (dat).myf
-
MGL suffix: (dat).mzf
-
MGL suffix: (dat).mxl
-
MGL suffix: (dat).myl
-
MGL suffix: (dat).mzl
-
Get first starting from give position (or last one if from<0) maximum along direction dir, and save its orthogonal coordinates in p1, p2.
-
-
-
-
-
-
MGL suffix: (dat).sum
-
MGL suffix: (dat).ax
-
MGL suffix: (dat).ay
-
MGL suffix: (dat).az
-
MGL suffix: (dat).aa
-
MGL suffix: (dat).wx
-
MGL suffix: (dat).wy
-
MGL suffix: (dat).wz
-
MGL suffix: (dat).wa
-
MGL suffix: (dat).sx
-
MGL suffix: (dat).sy
-
MGL suffix: (dat).sz
-
MGL suffix: (dat).sa
-
MGL suffix: (dat).kx
-
MGL suffix: (dat).ky
-
MGL suffix: (dat).kz
-
MGL suffix: (dat).ka
-
Gets zero-momentum (energy, I=\sum dat_i) and write first momentum (median, a = \sum \xi_i dat_i/I), second momentum (width, w^2 = \sum (\xi_i-a)^2 dat_i/I), third momentum (skewness, s = \sum (\xi_i-a)^3 dat_i/ I w^3) and fourth momentum (kurtosis, k = \sum (\xi_i-a)^4 dat_i / 3 I w^4) to variables. Here \xi is corresponding coordinate if dir is `'x'`, `'y'` or `'z'`. Otherwise median is a = \sum dat_i/N, width is w^2 = \sum (dat_i-a)^2/N and so on.
-
-
-
-
MGL suffix: (dat).fst
-
Find position (after specified in i, j, k) of first nonzero value of formula cond. Function return the data value at found position.
-
-
-
-
MGL suffix: (dat).lst
-
Find position (before specified in i, j, k) of last nonzero value of formula cond. Function return the data value at found position.
-
Does integral transformation of complex data real, imag on specified direction. The order of transformations is specified in string type: first character for x-dimension, second one for y-dimension, third one for z-dimension. The possible character are: `f` is forward Fourier transformation, `i` is inverse Fourier transformation, `s` is Sine transform, `c` is Cosine transform, `h` is Hankel transform, `n` or `` is no transformation.
-
-
-
-
MGL command: transformaDAT 'type' ampl phase
-
The same as previous but with specified amplitude ampl and phase phase of complex numbers.
-
-
-
-
MGL command: fourierreDat imDat 'dir'
-
MGL command: fouriercomplexDat 'dir'
-
Does Fourier transform of complex data re+i*im in directions dir. Result is placed back into re and im data arrays. If dir contain `i` then inverse Fourier is used.
-
-
-
-
MGL command: stfadRES real imag dn ['dir'='x']
-
Short time Fourier transformation for real and imaginary parts. Output is amplitude of partial Fourier of length dn. For example if dir=`x`, result will have size {int(nx/dn), dn, ny} and it will contain res[i,j,k]=|\sum_d^dn exp(I*j*d)*(real[i*dn+d,k]+I*imag[i*dn+d,k])|/dn.
-
-
-
-
MGL command: triangulatedat xdat ydat
-
Do Delone triangulation for 2d points and return result suitable for triplot and tricont. See Making regular data, for sample code and picture.
-
-
-
-
-
MGL command: tridmatRES ADAT BDAT CDAT DDAT 'how'
-
Get array as solution of tridiagonal system of equations A[i]*x[i-1]+B[i]*x[i]+C[i]*x[i+1]=D[i]. String how may contain:
-
-
`xyz` for solving along x-,y-,z-directions correspondingly;
-
`h` for solving along hexagonal direction at x-y plain (require square matrix);
-
`c` for using periodical boundary conditions;
-
`d` for for diffraction/diffuse calculation (i.e. for using -A[i]*D[i-1]+(2-B[i])*D[i]-C[i]*D[i+1] at right part instead of D[i]).
-
-
Data dimensions of arrays A, B, C should be equal. Also their dimensions need to be equal to all or to minor dimension(s) of array D. See PDE solving hints, for sample code and picture.
-
Solves equation du/dz = i*k0*ham(p,q,x,y,z,|u|)[u], where p=-i/k0*d/dx, q=-i/k0*d/dy are pseudo-differential operators. Parameters ini_re, ini_im specify real and imaginary part of initial field distribution. Parameters Min, Max set the bounding box for the solution. Note, that really this ranges are increased by factor 3/2 for purpose of reducing reflection from boundaries. Parameter dz set the step along evolutionary coordinate z. At this moment, simplified form of function ham is supported - all “mixed” terms (like `x*p`->x*d/dx) are excluded. For example, in 2D case this function is effectively ham = f(p,z) + g(x,z,u). However commutable combinations (like `x*q`->x*d/dy) are allowed. Here variable `u` is used for field amplitude |u|. This allow one solve nonlinear problems - for example, for nonlinear Shrodinger equation you may set ham="p^2 + q^2 - u^2". You may specify imaginary part for wave absorption, like ham = "p^2 + i*x*(x>0)". See also apde, qo2d, qo3d. See PDE solving hints, for sample code and picture.
-
Solves equation du/dz = i*k0*ham(p,q,x,y,z,|u|)[u], where p=-i/k0*d/dx, q=-i/k0*d/dy are pseudo-differential operators. Parameters ini_re, ini_im specify real and imaginary part of initial field distribution. Parameters Min, Max set the bounding box for the solution. Note, that really this ranges are increased by factor 3/2 for purpose of reducing reflection from boundaries. Parameter dz set the step along evolutionary coordinate z. The advanced and rather slow algorithm is used for taking into account both spatial dispersion and inhomogeneities of media [see A.A. Balakin, E.D. Gospodchikov, A.G. Shalashov, JETP letters v.104, p.690-695 (2016)]. Variable `u` is used for field amplitude |u|. This allow one solve nonlinear problems - for example, for nonlinear Shrodinger equation you may set ham="p^2 + q^2 - u^2". You may specify imaginary part for wave absorption, like ham = "p^2 + i*x*(x>0)". See also pde. See PDE solving hints, for sample code and picture.
-
Solves GO ray equation like dr/dt = d ham/dp, dp/dt = -d ham/dr. This is Hamiltonian equations for particle trajectory in 3D case. Here ham is Hamiltonian which may depend on coordinates `x`, `y`, `z`, momentums `p`=px, `q`=py, `v`=pz and time `t`: ham = H(x,y,z,p,q,v,t). The starting point (at t=0) is defined by variables r0, p0. Parameters dt and tmax specify the integration step and maximal time for ray tracing. Result is array of {x,y,z,p,q,v,t} with dimensions {7 * int(tmax/dt+1) }.
-
-
-
-
MGL command: odeRES 'df' 'var' ini [dt=0.1 tmax=10]
-
Solves ODE equations dx/dt = df(x). The functions df can be specified as string of `;`-separated textual formulas (argument var set the character ids of variables x[i]) or as callback function, which fill dx array for give x`s. Parameters ini, dt, tmax set initial values, time step and maximal time of the calculation. Function stop execution if NAN or INF values appears. Result is data array with dimensions {n * Nt}, where Nt <= int(tmax/dt+1)
-
-
-
-
MGL command: qo2dRES 'ham' ini_re ini_im ray [r=1 k0=100 xx yy]
-
Solves equation du/dt = i*k0*ham(p,q,x,y,|u|)[u], where p=-i/k0*d/dx, q=-i/k0*d/dy are pseudo-differential operators (see mglPDE() for details). Parameters ini_re, ini_im specify real and imaginary part of initial field distribution. Parameters ray set the reference ray, i.e. the ray around which the accompanied coordinate system will be maked. You may use, for example, the array created by ray function. Note, that the reference ray must be smooth enough to make accompanied coodrinates unambiguity. Otherwise errors in the solution may appear. If xx and yy are non-zero then Cartesian coordinates for each point will be written into them. See also pde, qo3d. See PDE solving hints, for sample code and picture.
-
-
-
-
-
MGL command: qo3dRES 'ham' ini_re ini_im ray [r=1 k0=100 xx yy zz]
-
Solves equation du/dt = i*k0*ham(p,q,v,x,y,z,|u|)[u], where p=-i/k0*d/dx, q=-i/k0*d/dy, v=-i/k0*d/dz are pseudo-differential operators (see mglPDE() for details). Parameters ini_re, ini_im specify real and imaginary part of initial field distribution. Parameters ray set the reference ray, i.e. the ray around which the accompanied coordinate system will be maked. You may use, for example, the array created by ray function. Note, that the reference ray must be smooth enough to make accompanied coodrinates unambiguity. Otherwise errors in the solution may appear. If xx and yy and zz are non-zero then Cartesian coordinates for each point will be written into them. See also pde, qo2d. See PDE solving hints, for sample code and picture.
-
-
-
-
-
MGL command: jacobianRES xdat ydat [zdat]
-
Computes the Jacobian for transformation {i,j,k} to {x,y,z} where initial coordinates {i,j,k} are data indexes normalized in range [0,1]. The Jacobian is determined by formula det||dr_\alpha/d\xi_\beta|| where r={x,y,z} and \xi={i,j,k}. All dimensions must be the same for all data arrays. Data must be 3D if all 3 arrays {x,y,z} are specified or 2D if only 2 arrays {x,y} are specified.
-
-
-
-
MGL command: triangulationRES xdat ydat
-
Computes triangulation for arbitrary placed points with coordinates {x,y} (i.e. finds triangles which connect points). MathGL use s-hull code for triangulation. The sizes of 1st dimension must be equal for all arrays x.nx=y.nx. Resulting array can be used in triplot or tricont functions for visualization of reconstructed surface. See Making regular data, for sample code and picture.
-
-
-
-
-
-
MGL command: ifs2dRES dat num [skip=20]
-
Computes num points {x[i]=res[0,i], y[i]=res[1,i]} for fractal using iterated function system. Matrix dat is used for generation according the formulas
-
Value dat[6,i] is used as weight factor for i-th row of matrix dat. At this first skip iterations will be omitted. Data array dat must have x-size greater or equal to 7. See also ifs3d, flame2d. See ifs2d sample, for sample code and picture.
-
-
-
-
MGL command: ifs3dRES dat num [skip=20]
-
Computes num points {x[i]=res[0,i], y[i]=res[1,i], z[i]=res[2,i]} for fractal using iterated function system. Matrix dat is used for generation according the formulas
-
Value dat[12,i] is used as weight factor for i-th row of matrix dat. At this first skip iterations will be omitted. Data array dat must have x-size greater or equal to 13. See also ifs2d. See ifs3d sample, for sample code and picture.
-
-
-
-
MGL command: ifsfileRES 'fname' 'name' num [skip=20]
-
Reads parameters of IFS fractal named name from file fname and computes num points for this fractal. At this first skip iterations will be omitted. See also ifs2d, ifs3d.
-
-
IFS file may contain several records. Each record contain the name of fractal (`binary` in the example below) and the body of fractal, which is enclosed in curly braces {}. Symbol `;` start the comment. If the name of fractal contain `(3D)` or `(3d)` then the 3d IFS fractal is specified. The sample below contain two fractals: `binary` - usual 2d fractal, and `3dfern (3D)` - 3d fractal. See also ifs2d, ifs3d.
-
Computes num points {x[i]=res[0,i], y[i]=res[1,i]} for "flame" fractal using iterated function system. Array func define "flame" function identificator (func[0,i,j]), its weight (func[0,i,j]) and arguments (func[2 ... 5,i,j]). Matrix dat set linear transformation of coordinates before applying the function. The resulting coordinates are
-
You can use arbitrary formulas of existed data arrays or constants as any argument of data processing or data plotting commands. There are only 2 limitations: formula shouldn`t contain spaces (to be recognized as single argument), and formula cannot be used as argument which will be (re)created by MGL command.
-
This chapter contain information about basic and advanced MathGL, hints and samples for all types of graphics. I recommend you read first 2 sections one after another and at least look on Hints section. Also I recommend you to look at General concepts and FAQ.
-
MGL script can be used by several manners. Each has positive and negative sides:
-
-
Using UDAV.
-
-
Positive sides are possibilities to view the plot at once and to modify it, rotate, zoom or switch on transparency or lighting by hands or by mouse. Negative side is the needness of the X-terminal.
-
Using command line tools.
-
-
Positive aspects are: batch processing of similar data set, for example, a set of resulting data files for different calculation parameters), running from the console program, including the cluster calculation), fast and automated drawing, saving pictures for further analysis, or demonstration). Negative sides are: the usage of the external program for picture viewing. Also, the data plotting is non-visual. So, you have to imagine the picture, view angles, lighting and so on) before the plotting. I recommend to use graphical window for determining the optimal parameters of plotting on the base of some typical data set. And later use these parameters for batch processing in console program.
-
-
In this case you can use the program: mglconv or mglview for viewing.
-
-
Using C/C++/... code.
-
-
You can easily execute MGL script within C/C++/Fortan code. This can be useful for fast data plotting, for example, in web applications, where textual string (MGL script) may contain all necessary information for plot. The basic C++ code may look as following
-
const char *mgl_script; // script itself, can be of type const wchar_t*
-mglGraph gr;
-mglParse pr;
-pr.Execute(&gr, mgl_script);
-
-
-
The simplest script is
-
box # draw bounding box
-axis # draw axis
-fplot 'x^3' # draw some function
-
-
Just type it in UDAV and press F5. Also you can save it in text file `test.mgl` and type in the console mglconv test.mgl what produce file `test.mgl.png` with resulting picture.
-
Now I show several non-obvious features of MGL: several subplots in a single picture, curvilinear coordinates, text printing and so on. Generally you may miss this section at first reading, but I don`t recommend it.
-
Let me demonstrate possibilities of plot positioning and rotation. MathGL has a set of functions: subplot, inplot, title, aspect and rotate and so on (see Subplots and rotation). The order of their calling is strictly determined. First, one changes the position of plot in image area (functions subplot, inplot and multiplot). Secondly, you can add the title of plot by title function. After that one may rotate the plot (command rotate). Finally, one may change aspects of axes (command aspect). The following code illustrates the aforesaid it:
-
Here I used function Puts for printing the text in arbitrary position of picture (see Text printing). Text coordinates and size are connected with axes. However, text coordinates may be everywhere, including the outside the bounding box. I`ll show its features later in Text features.
-
-
Note that several commands can be placed in a string if they are separated by `:` symbol.
-
-
-
-
More complicated sample show how to use most of positioning functions:
-
MathGL library can draw not only the bounding box but also the axes, grids, labels and so on. The ranges of axes and their origin (the point of intersection) are determined by functions SetRange(), SetRanges(), SetOrigin() (see Ranges (bounding box)). Ticks on axis are specified by function SetTicks, SetTicksVal, SetTicksTime (see Ticks). But usually
-
-
Command axis draws axes. Its textual string shows in which directions the axis or axes will be drawn (by default "xyz", function draws axes in all directions). Command grid draws grid perpendicularly to specified directions. Example of axes and grid drawing is:
-
Note, that MathGL can draw not only single axis (which is default). But also several axis on the plot (see right plots). The idea is that the change of settings does not influence on the already drawn graphics. So, for 2-axes I setup the first axis and draw everything concerning it. Then I setup the second axis and draw things for the second axis. Generally, the similar idea allows one to draw rather complicated plot of 4 axis with different ranges (see bottom left plot).
-
-
At this inverted axis can be created by 2 methods. First one is used in this sample - just specify minimal axis value to be large than maximal one. This method work well for 2D axis, but can wrongly place labels in 3D case. Second method is more general and work in 3D case too - just use aspect function with negative arguments. For example, following code will produce exactly the same result for 2D case, but 2nd variant will look better in 3D.
-
Another MathGL feature is fine ticks tunning. By default (if it is not changed by SetTicks function), MathGL try to adjust ticks positioning, so that they looks most human readable. At this, MathGL try to extract common factor for too large or too small axis ranges, as well as for too narrow ranges. Last one is non-common notation and can be disabled by SetTuneTicks function.
-
-
Also, one can specify its own ticks with arbitrary labels by help of SetTicksVal function. Or one can set ticks in time format. In last case MathGL will try to select optimal format for labels with automatic switching between years, months/days, hours/minutes/seconds or microseconds. However, you can specify its own time representation using formats described in http://www.manpagez.com/man/3/strftime/. Most common variants are `%X` for national representation of time, `%x` for national representation of date, `%Y` for year with century.
-
-
The sample code, demonstrated ticks feature is
-
subplot 3 3 0:title 'Usual axis'
-axis
-
-subplot 3 3 1:title 'Too big/small range'
-ranges -1000 1000 0 0.001:axis
-
-subplot 3 3 2:title 'LaTeX-like labels'
-axis 'F!'
-
-subplot 3 3 3:title 'Too narrow range'
-ranges 100 100.1 10 10.01:axis
-
-subplot 3 3 4:title 'No tuning, manual "+"'
-axis '+!'
-# for version <2.3 you can use
-#tuneticks off:axis
-
-subplot 3 3 5:title 'Template for ticks'
-xtick 'xxx:%g':ytick 'y:%g'
-axis
-
-xtick '':ytick '' # switch it off for other plots
-
-subplot 3 3 6:title 'No tuning, higher precision'
-axis '!4'
-
-subplot 3 3 7:title 'Manual ticks'
-ranges -pi pi 0 2
-xtick pi 3 '\pi'
-xtick 0.886 'x^*' on # note this will disable subticks drawing
-# or you can use
-#xtick -pi '\pi' -pi/2 '-\pi/2' 0 '0' 0.886 'x^*' pi/2 '\pi/2' pi 'pi'
-# or you can use
-#list v -pi -pi/2 0 0.886 pi/2 pi:xtick v '-\pi\n-\pi/2\n{}0\n{}x^*\n\pi/2\n\pi'
-axis:grid:fplot '2*cos(x^2)^2' 'r2'
-
-subplot 3 3 8:title 'Time ticks'
-xrange 0 3e5:ticktime 'x':axis
-
-
-
-
The last sample I want to show in this subsection is Log-axis. From MathGL`s point of view, the log-axis is particular case of general curvilinear coordinates. So, we need first define new coordinates (see also Curvilinear coordinates) by help of SetFunc or SetCoor functions. At this one should wary about proper axis range. So the code looks as following:
-
You can see that MathGL automatically switch to log-ticks as we define log-axis formula (in difference from v.1.*). Moreover, it switch to log-ticks for any formula if axis range will be large enough (see right bottom plot). Another interesting feature is that you not necessary define usual log-axis (i.e. when coordinates are positive), but you can define “minus-log” axis when coordinate is negative (see left bottom plot).
-
As I noted in previous subsection, MathGL support curvilinear coordinates. In difference from other plotting programs and libraries, MathGL uses textual formulas for connection of the old (data) and new (output) coordinates. This allows one to plot in arbitrary coordinates. The following code plots the line y=0, z=0 in Cartesian, polar, parabolic and spiral coordinates:
-
MathGL handle colorbar as special kind of axis. So, most of functions for axis and ticks setup will work for colorbar too. Colorbars can be in log-scale, and generally as arbitrary function scale; common factor of colorbar labels can be separated; and so on.
-
-
But of course, there are differences - colorbars usually located out of bounding box. At this, colorbars can be at subplot boundaries (by default), or at bounding box (if symbol `I` is specified). Colorbars can handle sharp colors. And they can be located at arbitrary position too. The sample code, which demonstrate colorbar features is:
-
call 'prepare2d'
-new v 9 'x'
-
-subplot 2 2 0:title 'Colorbar out of box':box
-colorbar '<':colorbar '>':colorbar '_':colorbar '^'
-
-subplot 2 2 1:title 'Colorbar near box':box
-colorbar '<I':colorbar '>I':colorbar '_I':colorbar '^I'
-
-subplot 2 2 2:title 'manual colors':box:contd v a
-colorbar v '<':colorbar v '>':colorbar v '_':colorbar v '^'
-
-subplot 2 2 3:title '':text -0.5 1.55 'Color positions' ':C' -2
-
-colorbar 'bwr>' 0.25 0:text -0.9 1.2 'Default'
-colorbar 'b{w,0.3}r>' 0.5 0:text -0.1 1.2 'Manual'
-
-crange 0.01 1e3
-colorbar '>' 0.75 0:text 0.65 1.2 'Normal scale'
-colorbar '>':text 1.35 1.2 'Log scale'
-
Box around the plot is rather useful thing because it allows one to: see the plot boundaries, and better estimate points position since box contain another set of ticks. MathGL provide special function for drawing such box - box function. By default, it draw black or white box with ticks (color depend on transparency type, see Types of transparency). However, you can change the color of box, or add drawing of rectangles at rear faces of box. Also you can disable ticks drawing, but I don`t know why anybody will want it. The sample code, which demonstrate box features is:
-
There are another unusual axis types which are supported by MathGL. These are ternary and quaternary axis. Ternary axis is special axis of 3 coordinates a, b, c which satisfy relation a+b+c=1. Correspondingly, quaternary axis is special axis of 4 coordinates a, b, c, d which satisfy relation a+b+c+d=1.
-
-
Generally speaking, only 2 of coordinates (3 for quaternary) are independent. So, MathGL just introduce some special transformation formulas which treat a as `x`, b as `y` (and c as `z` for quaternary). As result, all plotting functions (curves, surfaces, contours and so on) work as usual, but in new axis. You should use ternary function for switching to ternary/quaternary coordinates. The sample code is:
-
ranges 0 1 0 1 0 1
-new x 50 '0.25*(1+cos(2*pi*x))'
-new y 50 '0.25*(1+sin(2*pi*x))'
-new z 50 'x'
-new a 20 30 '30*x*y*(1-x-y)^2*(x+y<1)'
-new rx 10 'rnd':copy ry (1-rx)*rnd
-light on
-
-subplot 2 2 0:title 'Ordinary axis 3D':rotate 50 60
-box:axis:grid
-plot x y z 'r2':surf a '#'
-xlabel 'B':ylabel 'C':zlabel 'Z'
-
-subplot 2 2 1:title 'Ternary axis (x+y+t=1)':ternary 1
-box:axis:grid 'xyz' 'B;'
-plot x y 'r2':plot rx ry 'q^ ':cont a:line 0.5 0 0 0.75 'g2'
-xlabel 'B':ylabel 'C':tlabel 'A'
-
-subplot 2 2 2:title 'Quaternary axis 3D':rotate 50 60:ternary 2
-box:axis:grid 'xyz' 'B;'
-plot x y z 'r2':surf a '#'
-xlabel 'B':ylabel 'C':tlabel 'A':zlabel 'D'
-
-subplot 2 2 3:title 'Ternary axis 3D':rotate 50 60:ternary 1
-box:axis:grid 'xyz' 'B;'
-plot x y z 'r2':surf a '#'
-xlabel 'B':ylabel 'C':tlabel 'A':zlabel 'Z'
-
MathGL prints text by vector font. There are functions for manual specifying of text position (like Puts) and for its automatic selection (like Label, Legend and so on). MathGL prints text always in specified position even if it lies outside the bounding box. The default size of font is specified by functions SetFontSize* (see Font settings). However, the actual size of output string depends on subplot size (depends on functions SubPlot, InPlot). The switching of the font style (italic, bold, wire and so on) can be done for the whole string (by function parameter) or inside the string. By default MathGL parses TeX-like commands for symbols and indexes (see Font styles).
-
-
Text can be printed as usual one (from left to right), along some direction (rotated text), or along a curve. Text can be printed on several lines, divided by new line symbol `\n`.
-
-
Example of MathGL font drawing is:
-
call 'prepare1d'
-
-subplot 2 2 0 ''
-text 0 1 'Text can be in ASCII and in Unicode'
-text 0 0.6 'It can be \wire{wire}, \big{big} or #r{colored}'
-text 0 0.2 'One can change style in string: \b{bold}, \i{italic, \b{both}}'
-text 0 -0.2 'Easy to \a{overline} or \u{underline}'
-text 0 -0.6 'Easy to change indexes ^{up} _{down} @{center}'
-text 0 -1 'It parse TeX: \int \alpha \cdot \
-\sqrt3{sin(\pi x)^2 + \gamma_{i_k}} dx'
-
-subplot 2 2 1 ''
- text 0 0.5 '\sqrt{\frac{\alpha^{\gamma^2}+\overset 1{\big\infty}}{\sqrt3{2+b}}}' '@' -2
-text 0 -0.5 'Text can be printed\n{}on several lines'
-
-subplot 2 2 2 '':box:plot y(:,0)
-text y 'This is very very long string drawn along a curve' 'k'
-text y 'Another string drawn under a curve' 'Tr'
-
-subplot 2 2 3 '':line -1 -1 1 -1 'rA':text 0 -1 1 -1 'Horizontal'
-line -1 -1 1 1 'rA':text 0 0 1 1 'At angle' '@'
-line -1 -1 -1 1 'rA':text -1 0 -1 1 'Vertical'
-
-
-
-
You can change font faces by loading font files by function loadfont. Note, that this is long-run procedure. Font faces can be downloaded from MathGL website or from here. The sample code is:
-
Legend is one of standard ways to show plot annotations. Basically you need to connect the plot style (line style, marker and color) with some text. In MathGL, you can do it by 2 methods: manually using addlegend function; or use `legend` option (see Command options), which will use last plot style. In both cases, legend entries will be added into internal accumulator, which later used for legend drawing itself. clearlegend function allow you to remove all saved legend entries.
-
-
There are 2 features. If plot style is empty then text will be printed without indent. If you want to plot the text with indent but without plot sample then you need to use space `` as plot style. Such style `` will draw a plot sample (line with marker(s)) which is invisible line (i.e. nothing) and print the text with indent as usual one.
-
-
Command legend draw legend on the plot. The position of the legend can be selected automatic or manually. You can change the size and style of text labels, as well as setup the plot sample. The sample code demonstrating legend features is:
-
The last common thing which I want to show in this section is how one can cut off points from plot. There are 4 mechanism for that.
-
-
You can set one of coordinate to NAN value. All points with NAN values will be omitted.
-
-
You can enable cutting at edges by SetCut function. As result all points out of bounding box will be omitted.
-
-
You can set cutting box by SetCutBox function. All points inside this box will be omitted.
-
-
You can define cutting formula by SetCutOff function. All points for which the value of formula is nonzero will be omitted. Note, that this is the slowest variant.
-
-
-
Below I place the code which demonstrate last 3 possibilities:
-
Class mglData contains all functions for the data handling in MathGL (see Data processing). There are several matters why I use class mglData but not a single array: it does not depend on type of data (mreal or double), sizes of data arrays are kept with data, memory working is simpler and safer.
-
MathGL has functions for data processing: differentiating, integrating, smoothing and so on (for more detail, see Data processing). Let us consider some examples. The simplest ones are integration and differentiation. The direction in which operation will be performed is specified by textual string, which may contain symbols `x`, `y` or `z`. For example, the call of diff 'x' will differentiate data along `x` direction; the call of integrate 'xy' perform the double integration of data along `x` and `y` directions; the call of diff2 'xyz' will apply 3d Laplace operator to data and so on. Example of this operations on 2d array a=x*y is presented in code:
-
Data smoothing (command smooth) is more interesting and important. This function has single argument which define type of smoothing and its direction. Now 3 methods are supported: `3` - linear averaging by 3 points, `5` - linear averaging by 5 points, and default one - quadratic averaging by 5 points.
-
-
MathGL also have some amazing functions which is not so important for data processing as useful for data plotting. There are functions for finding envelope (useful for plotting rapidly oscillating data), for data sewing (useful to removing jumps on the phase), for data resizing (interpolation). Let me demonstrate it:
-
Finally one can create new data arrays on base of the existing one: extract slice, row or column of data (subdata), summarize along a direction(s) (sum), find distribution of data elements (hist) and so on.
-
-
Another interesting feature of MathGL is interpolation and root-finding. There are several functions for linear and cubic spline interpolation (see Interpolation). Also there is a function evaluate which do interpolation of data array for values of each data element of index data. It look as indirect access to the data elements.
-
-
This function have inverse function solve which find array of indexes at which data array is equal to given value (i.e. work as root finding). But solve function have the issue - usually multidimensional data (2d and 3d ones) have an infinite number of indexes which give some value. This is contour lines for 2d data, or isosurface(s) for 3d data. So, solve function will return index only in given direction, assuming that other index(es) are the same as equidistant index(es) of original data. Let me demonstrate this on the following sample.
-
-
zrange 0 1
-new x 20 30 '(x+2)/3*cos(pi*y)'
-new y 20 30 '(x+2)/3*sin(pi*y)'
-new z 20 30 'exp(-6*x^2-2*sin(pi*y)^2)'
-
-subplot 2 1 0:title 'Cartesian space':rotate 30 -40
-axis 'xyzU':box
-xlabel 'x':ylabel 'y'origin 1 1:grid 'xy'
-mesh x y z
-
-# section along 'x' direction
-solve u x 0.5 'x'
-var v u.nx 0 1
-evaluate yy y u v
-evaluate xx x u v
-evaluate zz z u v
-plot xx yy zz 'k2o'
-
-# 1st section along 'y' direction
-solve u1 x -0.5 'y'
-var v1 u1.nx 0 1
-evaluate yy y v1 u1
-evaluate xx x v1 u1
-evaluate zz z v1 u1
-plot xx yy zz 'b2^'
-
-# 2nd section along 'y' direction
-solve u2 x -0.5 'y' u1
-evaluate yy y v1 u2
-evaluate xx x v1 u2
-evaluate zz z v1 u2
-plot xx yy zz 'r2v'
-
-subplot 2 1 1:title 'Accompanied space'
-ranges 0 1 0 1:origin 0 0
-axis:box:xlabel 'i':ylabel 'j':grid2 z 'h'
-
-plot u v 'k2o':line 0.4 0.5 0.8 0.5 'kA'
-plot v1 u1 'b2^':line 0.5 0.15 0.5 0.3 'bA'
-plot v1 u2 'r2v':line 0.5 0.7 0.5 0.85 'rA'
-
Let me now show how to plot the data. Next section will give much more examples for all plotting functions. Here I just show some basics. MathGL generally has 2 types of plotting functions. Simple variant requires a single data array for plotting, other data (coordinates) are considered uniformly distributed in axis range. Second variant requires data arrays for all coordinates. It allows one to plot rather complex multivalent curves and surfaces (in case of parametric dependencies). Usually each function have one textual argument for plot style and accept options (see Command options).
-
-
Note, that the call of drawing function adds something to picture but does not clear the previous plots (as it does in Matlab). Another difference from Matlab is that all setup (like transparency, lightning, axis borders and so on) must be specified before plotting functions.
-
-
Let start for plots for 1D data. Term “1D data” means that data depend on single index (parameter) like curve in parametric form {x(i),y(i),z(i)}, i=1...n. The textual argument allow you specify styles of line and marks (see Line styles). If this parameter is empty '' then solid line with color from palette is used (see Palette and colors).
-
-
Below I shall show the features of 1D plotting on base of plot function. Let us start from sinus plot:
-
Style of line is not specified in plot function. So MathGL uses the solid line with first color of palette (this is blue). Next subplot shows array y1 with 2 rows:
-
As previously I did not specify the style of lines. As a result, MathGL again uses solid line with next colors in palette (there are green and red). Now let us plot a circle on the same subplot. The circle is parametric curve x=cos(\pi t), y=sin(\pi t). I will set the color of the circle (dark yellow, `Y`) and put marks `+` at point position:
-
new x 50 'cos(pi*x)'
-plot x y0 'Y+'
-
Note that solid line is used because I did not specify the type of line. The same picture can be achieved by plot and subdata functions. Let us draw ellipse by orange dash line:
-
plot y1(:,0) y1(:,1) 'q|'
-
-
Drawing in 3D space is mostly the same. Let us draw spiral with default line style. Now its color is 4-th color from palette (this is cyan):
-
subplot 2 2 2:rotate 60 40
-new z 50 'x'
-plot x y0 z:box
-
Functions plot and subdata make 3D curve plot but for single array. Use it to put circle marks on the previous plot:
-
Note that line style is empty `` here. Usage of other 1D plotting functions looks similar:
-
subplot 2 2 3:rotate 60 40
-bars x y0 z 'r':box
-
-
Surfaces surf and other 2D plots (see 2D plotting) are drown the same simpler as 1D one. The difference is that the string parameter specifies not the line style but the color scheme of the plot (see Color scheme). Here I draw attention on 4 most interesting color schemes. There is gray scheme where color is changed from black to white (string `kw`) or from white to black (string `wk`). Another scheme is useful for accentuation of negative (by blue color) and positive (by red color) regions on plot (string `"BbwrR"`). Last one is the popular “jet” scheme (string `"BbcyrR"`).
-
-
Now I shall show the example of a surface drawing. At first let us switch lightning on
-
light on
-
and draw the surface, considering coordinates x,y to be uniformly distributed in axis range
-
Color scheme was not specified. So previous color scheme is used. In this case it is default color scheme (“jet”) for the first plot. Next example is a sphere. The sphere is parametrically specified surface:
-
new x 50 40 '0.8*sin(pi*x)*cos(pi*y/2)'
-new y 50 40 '0.8*cos(pi*x)*cos(pi*y/2)'
-new z 50 40 '0.8*sin(pi*y/2)'
-subplot 2 2 1:rotate 60 40
-surf x y z 'BbwrR':box
-
I set color scheme to "BbwrR" that corresponds to red top and blue bottom of the sphere.
-
-
Surfaces will be plotted for each of slice of the data if nz>1. Next example draws surfaces for data arrays with nz=3:
-
Note, that it may entail a confusion. However, if one will use density plot then the picture will look better:
-
subplot 2 2 3:rotate 60 40
-dens a1:box
-
-
Drawing of other 2D plots is analogous. The only peculiarity is the usage of flag `#`. By default this flag switches on the drawing of a grid on plot (grid or mesh for plots in plain or in volume). However, for isosurfaces (including surfaces of rotation axial) this flag switches the face drawing off and figure becomes wired.
-
In this section I`ve included some small hints and advices for the improving of the quality of plots and for the demonstration of some non-trivial features of MathGL library. In contrast to previous examples I showed mostly the idea but not the whole drawing function.
-
As I noted above, MathGL functions (except the special one, like Clf()) do not erase the previous plotting but just add the new one. It allows one to draw “compound” plots easily. For example, popular Matlab command surfc can be emulated in MathGL by 2 calls:
-
Surf(a);
- Cont(a, "_"); // draw contours at bottom
-
Here a is 2-dimensional data for the plotting, -1 is the value of z-coordinate at which the contour should be plotted (at the bottom in this example). Analogously, one can draw density plot instead of contour lines and so on.
-
-
Another nice plot is contour lines plotted directly on the surface:
-
Light(true); // switch on light for the surface
- Surf(a, "BbcyrR"); // select 'jet' colormap for the surface
- Cont(a, "y"); // and yellow color for contours
-
The possible difficulties arise in black&white case, when the color of the surface can be close to the color of a contour line. In that case I may suggest the following code:
-
Light(true); // switch on light for the surface
- Surf(a, "kw"); // select 'gray' colormap for the surface
- CAxis(-1,0); // first draw for darker surface colors
- Cont(a, "w"); // white contours
- CAxis(0,1); // now draw for brighter surface colors
- Cont(a, "k"); // black contours
- CAxis(-1,1); // return color range to original state
-
The idea is to divide the color range on 2 parts (dark and bright) and to select the contrasting color for contour lines for each of part.
-
-
Similarly, one can plot flow thread over density plot of vector field amplitude (this is another amusing plot from Matlab) and so on. The list of compound graphics can be prolonged but I hope that the general idea is clear.
-
-
Just for illustration I put here following sample code:
-
call 'prepare2v'
-call 'prepare3d'
-new v 10:fill v -0.5 1:copy d sqrt(a^2+b^2)
-subplot 2 2 0:title 'Surf + Cont':rotate 50 60:light on:box
-surf a:cont a 'y'
-
-subplot 2 2 1 '':title 'Flow + Dens':light off:box
-flow a b 'br':dens d
-
-subplot 2 2 2:title 'Mesh + Cont':rotate 50 60:box
-mesh a:cont a '_'
-
-subplot 2 2 3:title 'Surf3 + ContF3':rotate 50 60:light on
-box:contf3 v c 'z' 0:contf3 v c 'x':contf3 v c
-cut 0 -1 -1 1 0 1.1
-contf3 v c 'z' c.nz-1:surf3 c -0.5
-
MathGL library has advanced features for setting and handling the surface transparency. The simplest way to add transparency is the using of command alpha. As a result, all further surfaces (and isosurfaces, density plots and so on) become transparent. However, their look can be additionally improved.
-
-
The value of transparency can be different from surface to surface. To do it just use SetAlphaDef before the drawing of the surface, or use option alpha (see Command options). If its value is close to 0 then the surface becomes more and more transparent. Contrary, if its value is close to 1 then the surface becomes practically non-transparent.
-
-
Also you can change the way how the light goes through overlapped surfaces. The function SetTranspType defines it. By default the usual transparency is used (`0`) - surfaces below is less visible than the upper ones. A “glass-like” transparency (`1`) has a different look - each surface just decreases the background light (the surfaces are commutable in this case).
-
-
A “neon-like” transparency (`2`) has more interesting look. In this case a surface is the light source (like a lamp on the dark background) and just adds some intensity to the color. At this, the library sets automatically the black color for the background and changes the default line color to white.
-
-
As example I shall show several plots for different types of transparency. The code is the same except the values of SetTranspType function:
-
You can easily make 3D plot and draw its x-,y-,z-projections (like in CAD) by using ternary function with arguments: 4 for Cartesian, 5 for Ternary and 6 for Quaternary coordinates. The sample code is:
-
ranges 0 1 0 1 0 1
-new x 50 '0.25*(1+cos(2*pi*x))'
-new y 50 '0.25*(1+sin(2*pi*x))'
-new z 50 'x'
-new a 20 30 '30*x*y*(1-x-y)^2*(x+y<1)'
-new rx 10 'rnd':new ry 10:fill ry '(1-v)*rnd' rx
-light on
-
-title 'Projection sample':ternary 4:rotate 50 60
-box:axis:grid
-plot x y z 'r2':surf a '#'
-xlabel 'X':ylabel 'Y':zlabel 'Z'
-
MathGL can add a fog to the image. Its switching on is rather simple - just use fog function. There is the only feature - fog is applied for whole image. Not to particular subplot. The sample code is:
-
call 'prepare2d'
-title 'Fog sample':rotate 50 60:light on
-fog 1
-box:surf a:cont a 'y'
-
In contrast to the most of other programs, MathGL supports several (up to 10) light sources. Moreover, the color each of them can be different: white (this is usual), yellow, red, cyan, green and so on. The use of several light sources may be interesting for the highlighting of some peculiarities of the plot or just to make an amusing picture. Note, each light source can be switched on/off individually. The sample code is:
-
Additionally, you can use local light sources and set to use diffuse reflection instead of specular one (by default) or both kinds. Note, I use attachlight command to keep light settings relative to subplot.
-
MathGL provide a set of functions for drawing primitives (see Primitives). Primitives are low level object, which used by most of plotting functions. Picture below demonstrate some of commonly used primitives.
-
Generally, you can create arbitrary new kind of plot using primitives. For example, MathGL don`t provide any special functions for drawing molecules. However, you can do it using only one type of primitives drop. The sample code is:
-
Moreover, some of special plots can be more easily produced by primitives rather than by specialized function. For example, Venn diagram can be produced by Error plot:
-
list x -0.3 0 0.3:list y 0.3 -0.3 0.3:list e 0.7 0.7 0.7
-title 'Venn-like diagram':alpha on
-error x y e e '!rgb@#o'
-
You see that you have to specify and fill 3 data arrays. The same picture can be produced by just 3 calls of circle function:
-
title 'Venn-like diagram':alpha on
-circle -0.3 0.3 0.7 'rr@'
-circle 0 -0.3 0.7 'gg@'
-circle 0.3 0.3 0.7 'bb@'
-
Of course, the first variant is more suitable if you need to plot a lot of circles. But for few ones the usage of primitives looks easy.
-
Short-time Fourier Analysis (stfa) is one of informative method for analyzing long rapidly oscillating 1D data arrays. It is used to determine the sinusoidal frequency and phase content of local sections of a signal as it changes over time.
-
-
MathGL can find and draw STFA result. Just to show this feature I give following sample. Initial data arrays is 1D arrays with step-like frequency. Exactly this you can see at bottom on the STFA plot. The sample code is:
-
new a 2000:new b 2000
-fill a 'cos(50*pi*x)*(x<-.5)+cos(100*pi*x)*(x<0)*(x>-.5)+\
-cos(200*pi*x)*(x<.5)*(x>0)+cos(400*pi*x)*(x>.5)'
-
-subplot 1 2 0 '<_':title 'Initial signal'
-plot a:axis:xlabel '\i t'
-
-subplot 1 2 1 '<_':title 'STFA plot'
-stfa a b 64:axis:ylabel '\omega' 0:xlabel '\i t'
-
Sometime ago I worked with mapping and have a question about its visualization. Let me remember you that mapping is some transformation rule for one set of number to another one. The 1d mapping is just an ordinary function - it takes a number and transforms it to another one. The 2d mapping (which I used) is a pair of functions which take 2 numbers and transform them to another 2 ones. Except general plots (like surfc, surfa) there is a special plot - Arnold diagram. It shows the area which is the result of mapping of some initial area (usually square).
-
-
I tried to make such plot in map. It shows the set of points or set of faces, which final position is the result of mapping. At this, the color gives information about their initial position and the height describes Jacobian value of the transformation. Unfortunately, it looks good only for the simplest mapping but for the real multivalent quasi-chaotic mapping it produces a confusion. So, use it if you like :).
-
-
The sample code for mapping visualization is:
-
new a 50 40 'x':new b 50 40 'y':zrange -2 2:text 0 0 '\to'
-subplot 2 1 0:text 0 1.1 '\{x, y\}' '' -2:box
-map a b 'brgk'
-
-subplot 2 1 1:box
-text 0 1.1 '\{\frac{x^3+y^3}{2}, \frac{x-y}{2}\}' '' -2
-fill a '(x^3+y^3)/2':fill b '(x-y)/2':map a b 'brgk'
-
functions subdata and evaluate for indirect access to data elements;
-
functions refill, gspline and datagrid which fill regular (rectangular) data array by interpolated values.
-
-
-
The usage of first category is rather straightforward and don`t need any special comments.
-
-
There is difference in indirect access functions. Function subdata use use step-like interpolation to handle correctly single nan values in the data array. Contrary, function evaluate use local spline interpolation, which give smoother output but spread nan values. So, subdata should be used for specific data elements (for example, for given column), and evaluate should be used for distributed elements (i.e. consider data array as some field). Following sample illustrates this difference:
-
subplot 1 1 0 '':title 'SubData vs Evaluate'
-new in 9 'x^3/1.1':plot in 'ko ':box
-new arg 99 '4*x+4'
-evaluate e in arg off:plot e 'b.'; legend 'Evaluate'
-subdata s in arg:plot s 'r.';legend 'SubData'
-legend 2
-
-
-
-
Example of datagrid usage is done in Making regular data. Here I want to show the peculiarities of refill and gspline functions. Both functions require argument(s) which provide coordinates of the data values, and return rectangular data array which equidistantly distributed in axis range. So, in opposite to evaluate function, refill and gspline can interpolate non-equidistantly distributed data. At this both functions refill and gspline provide continuity of 2nd derivatives along coordinate(s). However, refill is slower but give better (from human point of view) result than global spline gspline due to more advanced algorithm. Following sample illustrates this difference:
-
new x 10 '0.5+rnd':cumsum x 'x':norm x -1 1
-copy y sin(pi*x)/1.5
-subplot 2 2 0 '<_':title 'Refill sample'
-box:axis:plot x y 'o ':fplot 'sin(pi*x)/1.5' 'B:'
-new r 100:refill r x y:plot r 'r'
-
-subplot 2 2 1 '<_':title 'Global spline'
-box:axis:plot x y 'o ':fplot 'sin(pi*x)/1.5' 'B:'
-new r 100:gspline r x y:plot r 'r'
-
-new y 10 '0.5+rnd':cumsum y 'x':norm y -1 1
-copy xx x:extend xx 10
-copy yy y:extend yy 10:transpose yy
-copy z sin(pi*xx*yy)/1.5
-alpha on:light on
-subplot 2 2 2:title '2d regular':rotate 40 60
-box:axis:mesh xx yy z 'k'
-new rr 100 100:refill rr x y z:surf rr
-
-new xx 10 10 '(x+1)/2*cos(y*pi/2-1)'
-new yy 10 10 '(x+1)/2*sin(y*pi/2-1)'
-copy z sin(pi*xx*yy)/1.5
-subplot 2 2 3:title '2d non-regular':rotate 40 60
-box:axis:plot xx yy z 'ko '
-new rr 100 100:refill rr xx yy z:surf rr
-
Sometimes, one have only unregular data, like as data on triangular grids, or experimental results and so on. Such kind of data cannot be used as simple as regular data (like matrices). Only few functions, like dots, can handle unregular data as is.
-
-
However, one can use built in triangulation functions for interpolating unregular data points to a regular data grids. There are 2 ways. First way, one can use triangulation function to obtain list of vertexes for triangles. Later this list can be used in functions like triplot or tricont. Second way consist in usage of datagrid function, which fill regular data grid by interpolated values, assuming that coordinates of the data grid is equidistantly distributed in axis range. Note, you can use options (see Command options) to change default axis range as well as in other plotting functions.
-
new x 100 '2*rnd-1':new y 100 '2*rnd-1':copy z x^2-y^2
-# first way - plot triangular surface for points
-triangulate d x y
-title 'Triangulation'
-rotate 50 60:box:light on
-triplot d x y z:triplot d x y z '#k'
-# second way - make regular data and plot it
-new g 30 30:datagrid g x y z:mesh g 'm'
-
Using the hist function(s) for making regular distributions is one of useful fast methods to process and plot irregular data. Hist can be used to find some momentum of set of points by specifying weight function. It is possible to create not only 1D distributions but also 2D and 3D ones. Below I place the simplest sample code which demonstrate hist usage:
-
new x 10000 '2*rnd-1':new y 10000 '2*rnd-1':copy z exp(-6*(x^2+y^2))
-hist xx x z:norm xx 0 1:hist yy y z:norm yy 0 1
-multiplot 3 3 3 2 2 '':ranges -1 1 -1 1 0 1:box:dots x y z 'wyrRk'
-multiplot 3 3 0 2 1 '':ranges -1 1 0 1:box:bars xx
-multiplot 3 3 5 1 2 '':ranges 0 1 -1 1:box:barh yy
-subplot 3 3 2:text 0.5 0.5 'Hist and\n{}MultiPlot\n{}sample' 'a' -3
-
Nonlinear fitting is rather simple. All that you need is the data to fit, the approximation formula and the list of coefficients to fit (better with its initial guess values). Let me demonstrate it on the following simple example. First, let us use sin function with some random noise:
-
new dat 100 '0.4*rnd+0.1+sin(2*pi*x)'
-new in 100 '0.3+sin(2*pi*x)'
-
and plot it to see that data we will fit
-
title 'Fitting sample':yrange -2 2:box:axis:plot dat 'k. '
-
-
The next step is the fitting itself. For that let me specify an initial values ini for coefficients `abc` and do the fitting for approximation formula `a+b*sin(c*x)`
-
list ini 1 1 3:fit res dat 'a+b*sin(c*x)' 'abc' ini
-
Now display it
-
plot res 'r':plot in 'b'
-text -0.9 -1.3 'fitted:' 'r:L'
-putsfit 0 -1.8 'y = ' 'r'
-text 0 2.2 'initial: y = 0.3+sin(2\pi x)' 'b'
-
-
NOTE! the fitting results may have strong dependence on initial values for coefficients due to algorithm features. The problem is that in general case there are several local "optimums" for coefficients and the program returns only first found one! There are no guaranties that it will be the best. Try for example to set ini[3] = {0, 0, 0} in the code above.
-
-
The full sample code for nonlinear fitting is:
-
new dat 100 '0.4*rnd+0.1+sin(2*pi*x)'
-new in 100 '0.3+sin(2*pi*x)'
-list ini 1 1 3:fit res dat 'a+b*sin(c*x)' 'abc' ini
-title 'Fitting sample':yrange -2 2:box:axis:plot dat 'k. '
-plot res 'r':plot in 'b'
-text -0.9 -1.3 'fitted:' 'r:L'
-putsfit 0 -1.8 'y = ' 'r'
-text 0 2.2 'initial: y = 0.3+sin(2\pi x)' 'b'
-
Solving of Partial Differential Equations (PDE, including beam tracing) and ray tracing (or finding particle trajectory) are more or less common task. So, MathGL have several functions for that. There are ray for ray tracing, pde for PDE solving, qo2d for beam tracing in 2D case (see Global functions). Note, that these functions take “Hamiltonian” or equations as string values. And I don`t plan now to allow one to use user-defined functions. There are 2 reasons: the complexity of corresponding interface; and the basic nature of used methods which are good for samples but may not good for serious scientific calculations.
-
-
The ray tracing can be done by ray function. Really ray tracing equation is Hamiltonian equation for 3D space. So, the function can be also used for finding a particle trajectory (i.e. solve Hamiltonian ODE) for 1D, 2D or 3D cases. The function have a set of arguments. First of all, it is Hamiltonian which defined the media (or the equation) you are planning to use. The Hamiltonian is defined by string which may depend on coordinates `x`, `y`, `z`, time `t` (for particle dynamics) and momentums `p`=p_x, `q`=p_y, `v`=p_z. Next, you have to define the initial conditions for coordinates and momentums at `t`=0 and set the integrations step (default is 0.1) and its duration (default is 10). The Runge-Kutta method of 4-th order is used for integration.
-
This example calculate the reflection from linear layer (media with Hamiltonian `p^2+q^2-x-1`=p_x^2+p_y^2-x-1). This is parabolic curve. The resulting array have 7 columns which contain data for {x,y,z,p,q,v,t}.
-
-
The solution of PDE is a bit more complicated. As previous you have to specify the equation as pseudo-differential operator \hat H(x, \nabla) which is called sometime as “Hamiltonian” (for example, in beam tracing). As previously, it is defined by string which may depend on coordinates `x`, `y`, `z` (but not time!), momentums `p`=(d/dx)/i k_0, `q`=(d/dy)/i k_0 and field amplitude `u`=|u|. The evolutionary coordinate is `z` in all cases. So that, the equation look like du/dz = ik_0 H(x,y,\hat p, \hat q, |u|)[u]. Dependence on field amplitude `u`=|u| allows one to solve nonlinear problems too. For example, for nonlinear Shrodinger equation you may set ham="p^2 + q^2 - u^2". Also you may specify imaginary part for wave absorption, like ham = "p^2 + i*x*(x>0)" or ham = "p^2 + i1*x*(x>0)".
-
-
Next step is specifying the initial conditions at `z` equal to minimal z-axis value. The function need 2 arrays for real and for imaginary part. Note, that coordinates x,y,z are supposed to be in specified axis range. So, the data arrays should have corresponding scales. Finally, you may set the integration step and parameter k0=k_0. Also keep in mind, that internally the 2 times large box is used (for suppressing numerical reflection from boundaries) and the equation should well defined even in this extended range.
-
-
Final comment is concerning the possible form of pseudo-differential operator H. At this moment, simplified form of operator H is supported - all “mixed” terms (like `x*p`->x*d/dx) are excluded. For example, in 2D case this operator is effectively H = f(p,z) + g(x,z,u). However commutable combinations (like `x*q`->x*d/dy) are allowed for 3D case.
-
-
So, for example let solve the equation for beam deflected from linear layer and absorbed later. The operator will have the form `"p^2+q^2-x-1+i*0.5*(z+x)*(z>-x)"` that correspond to equation 1/ik_0 * du/dz + d^2 u/dx^2 + d^2 u/dy^2 + x * u + i (x+z)/2 * u = 0. This is typical equation for Electron Cyclotron (EC) absorption in magnetized plasmas. For initial conditions let me select the beam with plane phase front exp(-48*(x+0.7)^2). The corresponding code looks like this:
-
new re 128 'exp(-48*(x+0.7)^2)':new im 128
-pde a 'p^2+q^2-x-1+i*0.5*(z+x)*(z>-x)' re im 0.01 30
-transpose a
-subplot 1 1 0 '<_':title 'PDE solver'
-axis:xlabel '\i x':ylabel '\i z'
-crange 0 1:dens a 'wyrRk'
-fplot '-x' 'k|'
-text 0 0.95 'Equation: ik_0\partial_zu + \Delta u + x\cdot u +\
- i \frac{x+z}{2}\cdot u = 0\n{}absorption: (x+z)/2 for x+z>0'
-
-
-
-
The next example is example of beam tracing. Beam tracing equation is special kind of PDE equation written in coordinates accompanied to a ray. Generally this is the same parameters and limitation as for PDE solving but the coordinates are defined by the ray and by parameter of grid width w in direction transverse the ray. So, you don`t need to specify the range of coordinates. BUT there is limitation. The accompanied coordinates are well defined only for smooth enough rays, i.e. then the ray curvature K (which is defined as 1/K^2 = (|r''|^2 |r'|^2 - (r'', r'')^2)/|r'|^6) is much large then the grid width: K>>w. So, you may receive incorrect results if this condition will be broken.
-
-
You may use following code for obtaining the same solution as in previous example:
-
define $1 'p^2+q^2-x-1+i*0.5*(y+x)*(y>-x)'
-subplot 1 1 0 '<_':title 'Beam and ray tracing'
-ray r $1 -0.7 -1 0 0 0.5 0 0.02 2:plot r(0) r(1) 'k'
-axis:xlabel '\i x':ylabel '\i z'
-new re 128 'exp(-48*x^2)':new im 128
-new xx 1:new yy 1
-qo2d a $1 re im r 1 30 xx yy
-crange 0 1:dens xx yy a 'wyrRk':fplot '-x' 'k|'
-text 0 0.85 'absorption: (x+y)/2 for x+y>0'
-text 0.7 -0.05 'central ray'
-
-
-
-
Note, the pde is fast enough and suitable for many cases routine. However, there is situations then media have both together: strong spatial dispersion and spatial inhomogeneity. In this, case the pde will produce incorrect result and you need to use advanced PDE solver apde. For example, a wave beam, propagated in plasma, described by Hamiltonian exp(-x^2-p^2), will have different solution for using of simplification and advanced PDE solver:
-
Here I want say a few words of plotting phase plains. Phase plain is name for system of coordinates x, x', i.e. a variable and its time derivative. Plot in phase plain is very useful for qualitative analysis of an ODE, because such plot is rude (it topologically the same for a range of ODE parameters). Most often the phase plain {x, x'} is used (due to its simplicity), that allows to analyze up to the 2nd order ODE (i.e. x''+f(x,x')=0).
-
-
The simplest way to draw phase plain in MathGL is using flow function(s), which automatically select several points and draw flow threads. If the ODE have an integral of motion (like Hamiltonian H(x,x')=const for dissipation-free case) then you can use cont function for plotting isolines (contours). In fact. isolines are the same as flow threads, but without arrows on it. Finally, you can directly solve ODE using ode function and plot its numerical solution.
-
-
Let demonstrate this for ODE equation x''-x+3*x^2=0. This is nonlinear oscillator with square nonlinearity. It has integral H=y^2+2*x^3-x^2=Const. Also it have 2 typical stationary points: saddle at {x=0, y=0} and center at {x=1/3, y=0}. Motion at vicinity of center is just simple oscillations, and is stable to small variation of parameters. In opposite, motion around saddle point is non-stable to small variation of parameters, and is very slow. So, calculation around saddle points are more difficult, but more important. Saddle points are responsible for solitons, stochasticity and so on.
-
-
So, let draw this phase plain by 3 different methods. First, draw isolines for H=y^2+2*x^3-x^2=Const - this is simplest for ODE without dissipation. Next, draw flow threads - this is straightforward way, but the automatic choice of starting points is not always optimal. Finally, use ode to check the above plots. At this we need to run ode in both direction of time (in future and in the past) to draw whole plain. Alternatively, one can put starting points far from (or at the bounding box as done in flow) the plot, but this is a more complicated. The sample code is:
-
There is common task in optics to determine properties of wave pulses or wave beams. MathGL provide special function pulse which return the pulse properties (maximal value, center of mass, width and so on). Its usage is rather simple. Here I just illustrate it on the example of Gaussian pulse, where all parameters are obvious.
-
subplot 1 1 0 '<_':title 'Pulse sample'
-# first prepare pulse itself
-new a 100 'exp(-6*x^2)'
-
-# get pulse parameters
-pulse b a 'x'
-
-# positions and widths are normalized on the number of points. So, set proper axis scale.
-ranges 0 a.nx-1 0 1
-axis:plot a # draw pulse and axis
-
-# now visualize found pulse properties
-define m a.max # maximal amplitude
-# approximate position of maximum
-line b(1) 0 b(1) m 'r='
-# width at half-maximum (so called FWHM)
-line b(1)-b(3)/2 0 b(1)-b(3)/2 m 'm|'
-line b(1)+b(3)/2 0 b(1)+b(3)/2 m 'm|'
-line 0 0.5*m a.nx-1 0.5*m 'h'
-# parabolic approximation near maximum
-new x 100 'x'
-plot b(0)*(1-((x-b(1))/b(2))^2) 'g'
-
Command options allow the easy setup of the selected plot by changing global settings only for this plot. Often, options are used for specifying the range of automatic variables (coordinates). However, options allows easily change plot transparency, numbers of line or faces to be drawn, or add legend entries. The sample function for options usage is:
-
new a 31 41 '-pi*x*exp(-(y+1)^2-4*x^2)'
-alpha on:light on
-subplot 2 2 0:title 'Options for coordinates':rotate 40 60:box
-surf a 'r';yrange 0 1
-surf a 'b';yrange 0 -1
-
-subplot 2 2 1:title 'Option "meshnum"':rotate 40 60:box
-mesh a 'r'; yrange 0 1
-mesh a 'b';yrange 0 -1; meshnum 5
-
-subplot 2 2 2:title 'Option "alpha"':rotate 40 60:box
-surf a 'r';yrange 0 1; alpha 0.7
-surf a 'b';yrange 0 -1; alpha 0.3
-
-subplot 2 2 3 '<_':title 'Option "legend"'
-fplot 'x^3' 'r'; legend 'y = x^3'
-fplot 'cos(pi*x)' 'b'; legend 'y = cos \pi x'
-box:axis:legend 2
-
As I have noted before, the change of settings will influence only for the further plotting commands. This allows one to create “template” function which will contain settings and primitive drawing for often used plots. Correspondingly one may call this template-function for drawing simplification.
-
-
For example, let one has a set of points (experimental or numerical) and wants to compare it with theoretical law (for example, with exponent law \exp(-x/2), x \in [0, 20]). The template-function for this task is:
-
At this, one will only write a few lines for data drawing:
-
template(gr); // apply settings and default drawing from template
- mglData dat("fname.dat"); // load the data
- // and draw it (suppose that data file have 2 columns)
- gr->Plot(dat.SubData(0),dat.SubData(1),"bx ");
-
A template-function can also contain settings for font, transparency, lightning, color scheme and so on.
-
-
I understand that this is obvious thing for any professional programmer, but I several times receive suggestion about “templates” ... So, I decide to point out it here.
-
One can easily create stereo image in MathGL. Stereo image can be produced by making two subplots with slightly different rotation angles. The corresponding code looks like this:
-
call 'prepare2d'
-light on
-subplot 2 1 0:rotate 50 60+1:box:surf a
-subplot 2 1 1:rotate 50 60-1:box:surf a
-
By default MathGL save all primitives in memory, rearrange it and only later draw them on bitmaps. Usually, this speed up drawing, but may require a lot of memory for plots which contain a lot of faces (like cloud, dew). You can use quality function for setting to use direct drawing on bitmap and bypassing keeping any primitives in memory. This function also allow you to decrease the quality of the resulting image but increase the speed of the drawing.
-
-
The code for lower memory usage looks like this:
-
quality 6 # firstly, set to draw directly on bitmap
-for $1 0 1000
- sphere 2*rnd-1 2*rnd-1 0.05
-next
-
MathGL have possibilities to write textual information into file with variable values by help of save command. This is rather useful for generating an ini-files or preparing human-readable textual files. For example, lets create some textual file
-
subplot 1 1 0 '<_':title 'Save and scanfile sample'
-list a 1 -1 0
-save 'This is test: 0 -> ',a(0),' q' 'test.txt' 'w'
-save 'This is test: 1 -> ',a(1),' q' 'test.txt'
-save 'This is test: 2 -> ',a(2),' q' 'test.txt'
-
It contents look like
-
This is test: 0 -> 1 q
-This is test: 1 -> -1 q
-This is test: 2 -> 0 q
-
Note, that I use option `w` at first call of save to overwrite the contents of the file.
-
-
Let assume now that you want to read this values (i.e. [[0,1],[1,-1],[2,0]]) from the file. You can use scanfile for that. The desired values was written using template `This is test: %g -> %g q`. So, just use
-
scanfile a 'test.txt' 'This is test: %g -> %g'
-
and plot it to for assurance
-
ranges a(0) a(1):axis:plot a(0) a(1) 'o'
-
-
Note, I keep only the leading part of template (i.e. `This is test: %g -> %g` instead of `This is test: %g -> %g q`), because there is no important for us information after the second number in the line.
-
Sometimes output plots contain surfaces with a lot of points, and some vector primitives (like axis, text, curves, etc.). Using vector output formats (like EPS or SVG) will produce huge files with possible loss of smoothed lighting. Contrary, the bitmap output may cause the roughness of text and curves. Hopefully, MathGL have a possibility to combine bitmap output for surfaces and vector one for other primitives in the same EPS file, by using rasterize command.
-
-
The idea is to prepare part of picture with surfaces or other "heavy" plots and produce the background image from them by help of rasterize command. Next, we draw everything to be saved in vector form (text, curves, axis and etc.). Note, that you need to clear primitives (use clf command) after rasterize if you want to disable duplication of surfaces in output files (like EPS). Note, that some of output formats (like 3D ones, and TeX) don`t support the background bitmap, and use clf for them will cause the loss of part of picture.
-
-
The sample code is:
-
# first draw everything to be in bitmap output
-fsurf 'x^2+y^2' '#';value 10
-
-rasterize # set above plots as bitmap background
-clf # clear primitives, to exclude them from file
-
-# now draw everything to be in vector output
-axis:box
-
-# and save file
-write 'fname.eps'
-
Check that points of the plot are located inside the bounding box and resize the bounding box using ranges function. Check that the data have correct dimensions for selected type of plot. Sometimes the light reflection from flat surfaces (like, dens) can look as if the plot were absent.
-
-
-
I can not find some special kind of plot.
-
Most “new” types of plots can be created by using the existing drawing functions. For example, the surface of curve rotation can be created by a special function torus, or as a parametrically specified surface by surf. See also, Hints. If you can not find a specific type of plot, please e-mail me and this plot will appear in the next version of MathGL library.
-
-
-
How can I print in Russian/Spanish/Arabic/Japanese, and so on?
-
The standard way is to use Unicode encoding for the text output. But the MathGL library also has interface for 8-bit (char *) strings with internal conversion to Unicode. This conversion depends on the current locale OS.
-
-
-
How can I exclude a point or a region of plot from the drawing?
-
There are 3 general ways. First, the point with nan value as one of the coordinates (including color/alpha range) will never be plotted. Second, special functions define the condition when the points should be omitted (see Cutting). Last, you may change the transparency of a part of the plot by the help of functions surfa, surf3a (see Dual plotting). In last case the transparency is switched on smoothly.
-
-
-
How many people write this library?
-
Most of the library was written by one person. This is a result of nearly a year of work (mostly in the evening and on holidays): I spent half a year to write the kernel and half a year to a year on extending, improving the library and writing documentation. This process continues now :). The build system (cmake files) was written mostly by D.Kulagin, and the export to PRC/PDF was written mostly by M.Vidassov.
-
-
-
How can I display a bitmap on the figure?
-
You can import data by command import and display it by dens function. For example, for black-and-white bitmap you can use the code: import bmp 'fname.png' 'wk':dens bmp 'wk'.
-
-
-
-
How can I create 3D in PDF?
-
Just use command write fname.pdf, which create PDF file if enable-pdf=ON at MathGL configure.
-
-
-
How can I create TeX figure?
-
Just use command write fname.tex, which create LaTeX files with figure itself `fname.tex`, with MathGL colors `mglcolors.tex` and main file `mglmain.tex`. Last one can be used for viewing image by command like pdflatex mglmain.tex.
-
-
-
-
How I can change the font family?
-
First, you should download new font files from here or from here. Next, you should load the font files into by the following command: loadfont 'fontname'. Here fontname is the base font name like `STIX`. Use loadfont '' to start using the default font.
-
-
-
How can I draw tick out of a bounding box?
-
Just set a negative value in ticklen. For example, use ticklen -0.1.
-
-
-
How can I prevent text rotation?
-
Just use rotatetext off. Also you can use axis style `U` for disable only tick labels rotation.
-
-
-
How can I draw equal axis range even for rectangular image?
-
Just use aspect nan nan for each subplot, or at the beginning of the drawing.
-
-
-
How I can set transparent background?
-
Just use code like clf 'r{A5}' or prepare PNG file and set it as background image by call background 'fname.png'.
-
-
-
How I can reduce "white" edges around bounding box?
-
The simplest way is to use subplot style. However, you should be careful if you plan to add colorbar or rotate plot - part of plot can be invisible if you will use non-default subplot style.
-
-
-
Can I combine bitmap and vector output in EPS?
-
Yes. Sometimes you may have huge surface and a small set of curves and/or text on the plot. You can use function rasterize just after making surface plot. This will put all plot to bitmap background. At this later plotting will be in vector format. For example, you can do something like following:
-
surf x y z
-rasterize # make surface as bitmap
-axis
-write 'fname.eps'
-
Function axial draw surfaces of rotation for contour lines. You can draw wire surfaces (`#` style) or ones rotated in other directions (`x`, `z` styles).
-
Function bars draw vertical bars. It have a lot of options: bar-above-bar (`a` style), fall like (`f` style), 2 colors for positive and negative values, wired bars (`#` style), 3D variant.
-
Function candle draw candlestick chart. This is a combination of a line-chart and a bar-chart, in that each bar represents the range of price movement over a given time interval.
-
-
MGL code:
-
new y 30 'sin(pi*x/2)^2'
-subplot 1 1 0 '':title 'Candle plot (default)'
-yrange 0 1:box
-candle y y/2 (y+1)/2
-
Function chart draw colored boxes with width proportional to data values. Use `` for empty box. It produce well known pie chart if drawn in polar coordinates.
-
Function cloud draw cloud-like object which is less transparent for higher data values. Similar plot can be created using many (about 10...20 - surf3a a a;value 10) isosurfaces surf3a.
-
call 'prepare2v'
-call 'prepare3d'
-new v 10:fill v -0.5 1:copy d sqrt(a^2+b^2)
-subplot 2 2 0:title 'Surf + Cont':rotate 50 60:light on:box:surf a:cont a 'y'
-subplot 2 2 1 '':title 'Flow + Dens':light off:box:flow a b 'br':dens d
-subplot 2 2 2:title 'Mesh + Cont':rotate 50 60:box:mesh a:cont a '_'
-subplot 2 2 3:title 'Surf3 + ContF3':rotate 50 60:light on
-box:contf3 v c 'z' 0:contf3 v c 'x':contf3 v c
-cut 0 -1 -1 1 0 1.1
-contf3 v c 'z' c.nz-1:surf3 c -0.5
-
Function cont draw contour lines for surface. You can select automatic (default) or manual levels for contours, print contour labels, draw it on the surface (default) or at plane (as Dens).
-
-
MGL code:
-
call 'prepare2d'
-list v -0.5 -0.15 0 0.15 0.5
-subplot 2 2 0:title 'Cont plot (default)':rotate 50 60:box:cont a
-subplot 2 2 1:title 'manual levels':rotate 50 60:box:cont v a
-subplot 2 2 2:title '"\_" and "." styles':rotate 50 60:box:cont a '_':cont a '_.2k'
-subplot 2 2 3 '':title '"t" style':box:cont a 't'
-
Functions contz, conty, contx draw contour lines on plane perpendicular to corresponding axis. One of possible application is drawing projections of 3D field.
-
-
MGL code:
-
call 'prepare3d'
-title 'Cont[XYZ] sample':rotate 50 60:box
-contx {sum c 'x'} '' -1:conty {sum c 'y'} '' 1:contz {sum c 'z'} '' -1
-
Functions contfz, contfy, contfx, draw filled contours on plane perpendicular to corresponding axis. One of possible application is drawing projections of 3D field.
-
-
MGL code:
-
call 'prepare3d'
-title 'ContF[XYZ] sample':rotate 50 60:box
-contfx {sum c 'x'} '' -1:contfy {sum c 'y'} '' 1:contfz {sum c 'z'} '' -1
-
new a 100 'exp(-10*x^2)'
-new b 100 'exp(-10*(x+0.5)^2)'
-yrange 0 1
-subplot 1 2 0 '_':title 'Input fields'
-plot a:plot b:box:axis
-correl r a b 'x'
-norm r 0 1:swap r 'x' # make it human readable
-subplot 1 2 1 '_':title 'Correlation of a and b'
-plot r 'r':axis:box
-line 0.5 0 0.5 1 'B|'
-
new a 40 50 60 'exp(-x^2-4*y^2-16*z^2)'
-light on:alpha on
-copy b a:diff b 'x':subplot 5 3 0:call 'splot'
-copy b a:diff2 b 'x':subplot 5 3 1:call 'splot'
-copy b a:cumsum b 'x':subplot 5 3 2:call 'splot'
-copy b a:integrate b 'x':subplot 5 3 3:call 'splot'
-mirror b 'x':subplot 5 3 4:call 'splot'
-copy b a:diff b 'y':subplot 5 3 5:call 'splot'
-copy b a:diff2 b 'y':subplot 5 3 6:call 'splot'
-copy b a:cumsum b 'y':subplot 5 3 7:call 'splot'
-copy b a:integrate b 'y':subplot 5 3 8:call 'splot'
-mirror b 'y':subplot 5 3 9:call 'splot'
-copy b a:diff b 'z':subplot 5 3 10:call 'splot'
-copy b a:diff2 b 'z':subplot 5 3 11:call 'splot'
-copy b a:cumsum b 'z':subplot 5 3 12:call 'splot'
-copy b a:integrate b 'z':subplot 5 3 13:call 'splot'
-mirror b 'z':subplot 5 3 14:call 'splot'
-stop
-func splot 0
-title 'max=',b.max:norm b -1 1 on:rotate 70 60:box:surf3 b
-return
-
new a 40 50 60 'exp(-x^2-4*y^2-16*z^2)'
-light on:alpha on
-copy b a:sinfft b 'x':subplot 5 3 0:call 'splot'
-copy b a:cosfft b 'x':subplot 5 3 1:call 'splot'
-copy b a:hankel b 'x':subplot 5 3 2:call 'splot'
-copy b a:swap b 'x':subplot 5 3 3:call 'splot'
-copy b a:smooth b 'x':subplot 5 3 4:call 'splot'
-copy b a:sinfft b 'y':subplot 5 3 5:call 'splot'
-copy b a:cosfft b 'y':subplot 5 3 6:call 'splot'
-copy b a:hankel b 'y':subplot 5 3 7:call 'splot'
-copy b a:swap b 'y':subplot 5 3 8:call 'splot'
-copy b a:smooth b 'y':subplot 5 3 9:call 'splot'
-copy b a:sinfft b 'z':subplot 5 3 10:call 'splot'
-copy b a:cosfft b 'z':subplot 5 3 11:call 'splot'
-copy b a:hankel b 'z':subplot 5 3 12:call 'splot'
-copy b a:swap b 'z':subplot 5 3 13:call 'splot'
-copy b a:smooth b 'z':subplot 5 3 14:call 'splot'
-stop
-func splot 0
-title 'max=',b.max:norm b -1 1 on:rotate 70 60:box
-surf3 b 0.5:surf3 b -0.5
-return
-
Functions densz, densy, densx draw density plot on plane perpendicular to corresponding axis. One of possible application is drawing projections of 3D field.
-
-
MGL code:
-
call 'prepare3d'
-title 'Dens[XYZ] sample':rotate 50 60:box
-densx {sum c 'x'} '' -1:densy {sum c 'y'} '' 1:densz {sum c 'z'} '' -1
-
define n 32 #number of points
-define m 20 # number of iterations
-define dt 0.01 # time step
-new res n m+1
-ranges -1 1 0 m*dt 0 1
-
-#tridmat periodic variant
-new !a n 'i',dt*(n/2)^2/2
-copy !b !(1-2*a)
-
-new !u n 'exp(-6*x^2)'
-put res u all 0
-for $i 0 m
-tridmat u a b a u 'xdc'
-put res u all $i+1
-next
-subplot 2 2 0 '<_':title 'Tridmat, periodic b.c.'
-axis:box:dens res
-
-#fourier variant
-new k n:fillsample k 'xk'
-copy !e !exp(-i1*dt*k^2)
-
-new !u n 'exp(-6*x^2)'
-put res u all 0
-for $i 0 m
-fourier u 'x'
-multo u e
-fourier u 'ix'
-put res u all $i+1
-next
-subplot 2 2 1 '<_':title 'Fourier method'
-axis:box:dens res
-
-#tridmat zero variant
-new !u n 'exp(-6*x^2)'
-put res u all 0
-for $i 0 m
-tridmat u a b a u 'xd'
-put res u all $i+1
-next
-subplot 2 2 2 '<_':title 'Tridmat, zero b.c.'
-axis:box:dens res
-
-#diffract exp variant
-new !u n 'exp(-6*x^2)'
-define q dt*(n/2)^2/8 # need q<0.4 !!!
-put res u all 0
-for $i 0 m
-for $j 1 8 # due to smaller dt
-diffract u 'xe' q
-next
-put res u all $i+1
-next
-subplot 2 2 3 '<_':title 'Diffract, exp b.c.'
-axis:box:dens res
-
Function dots is another way to draw irregular points. Dots use color scheme for coloring (see Color scheme).
-
-
MGL code:
-
new t 2000 'pi*(rnd-0.5)':new f 2000 '2*pi*rnd'
-copy x 0.9*cos(t)*cos(f):copy y 0.9*cos(t)*sin(f):copy z 0.6*sin(t):copy c cos(2*t)
-subplot 2 2 0:title 'Dots sample':rotate 50 60
-box:dots x y z
-alpha on
-subplot 2 2 1:title 'add transparency':rotate 50 60
-box:dots x y z c
-subplot 2 2 2:title 'add colorings':rotate 50 60
-box:dots x y z x c
-subplot 2 2 3:title 'Only coloring':rotate 50 60
-box:tens x y z x ' .'
-
import dat 'Equirectangular-projection.jpg' 'BbGYw' -1 1
-subplot 1 1 0 '<>':title 'Earth in 3D':rotate 40 60
-copy phi dat 'pi*x':copy tet dat 'pi*y/2'
-copy x cos(tet)*cos(phi)
-copy y cos(tet)*sin(phi)
-copy z sin(tet)
-
-light on
-surfc x y z dat 'BbGYw'
-contp [-0.51,-0.51] x y z dat 'y'
-
Function error draw error boxes around the points. You can draw default boxes or semi-transparent symbol (like marker, see Line styles). Also you can set individual color for each box. See also error2 sample.
-
new a 100 100 'x^2*y':new b 100 100
-export a 'test_data.png' 'BbcyrR' -1 1
-import b 'test_data.png' 'BbcyrR' -1 1
-subplot 2 1 0 '':title 'initial':box:dens a
-subplot 2 1 1 '':title 'imported':box:dens b
-
Function fall draw waterfall surface. You can use meshnum for changing number of lines to be drawn. Also you can use `x` style for drawing lines in other direction.
-
-
MGL code:
-
call 'prepare2d'
-title 'Fall plot':rotate 50 60:box:fall a
-
new dat 100 '0.4*rnd+0.1+sin(2*pi*x)'
-new in 100 '0.3+sin(2*pi*x)'
-list ini 1 1 3:fit res dat 'a+b*sin(c*x)' 'abc' ini
-title 'Fitting sample':yrange -2 2:box:axis:plot dat 'k. '
-plot res 'r':plot in 'b'
-text -0.9 -1.3 'fitted:' 'r:L'
-putsfit 0 -1.8 'y = ' 'r':text 0 2.2 'initial: y = 0.3+sin(2\pi x)' 'b'
-
Function flame2d generate points for flame fractals in 2d case.
-
-
MGL code:
-
list A [0.33,0,0,0.33,0,0,0.2] [0.33,0,0,0.33,0.67,0,0.2] [0.33,0,0,0.33,0.33,0.33,0.2]\
- [0.33,0,0,0.33,0,0.67,0.2] [0.33,0,0,0.33,0.67,0.67,0.2]
-new B 2 3 A.ny '0.3'
-put B 3 0 0 -1
-put B 3 0 1 -1
-put B 3 0 2 -1
-flame2d fx fy A B 1000000
-subplot 1 1 0 '<_':title 'Flame2d sample'
-ranges fx fy:box:axis
-plot fx fy 'r#o ';size 0.05
-
Function flow is another standard way to visualize vector fields - it draw lines (threads) which is tangent to local vector field direction. MathGL draw threads from edges of bounding box and from central slices. Sometimes it is not most appropriate variant - you may want to use flowp to specify manual position of threads. The color scheme is used for coloring (see Color scheme). At this warm color corresponds to normal flow (like attractor), cold one corresponds to inverse flow (like source).
-
-
MGL code:
-
call 'prepare2v'
-call 'prepare3v'
-subplot 2 2 0 '':title 'Flow plot (default)':box:flow a b
-subplot 2 2 1 '':title '"v" style':box:flow a b 'v'
-subplot 2 2 2 '':title '"#" and "." styles':box:flow a b '#':flow a b '.2k'
-subplot 2 2 3:title '3d variant':rotate 50 60:box:flow ex ey ez
-
Function flow3 draw flow threads, which start from given plane.
-
-
MGL code:
-
call 'prepare3v'
-subplot 2 2 0:title 'Flow3 plot (default)':rotate 50 60:box
-flow3 ex ey ez
-subplot 2 2 1:title '"v" style, from boundary':rotate 50 60:box
-flow3 ex ey ez 'v' 0
-subplot 2 2 2:title '"t" style':rotate 50 60:box
-flow3 ex ey ez 't' 0
-subplot 2 2 3:title 'from \i z planes':rotate 50 60:box
-flow3 ex ey ez 'z' 0
-flow3 ex ey ez 'z' 9
-
subplot 1 1 0 '':title 'SubData vs Evaluate'
-new in 9 'x^3/1.1':plot in 'ko ':box
-new arg 99 '4*x+4'
-evaluate e in arg off:plot e 'b.'; legend 'Evaluate'
-subdata s in arg:plot s 'r.';legend 'SubData'
-legend 2
-
Function ohlc draw Open-High-Low-Close diagram. This diagram show vertical line for between maximal(high) and minimal(low) values, as well as horizontal lines before/after vertical line for initial(open)/final(close) values of some process.
-
-
MGL code:
-
new o 10 '0.5*sin(pi*x)'
-new c 10 '0.5*sin(pi*(x+2/9))'
-new l 10 '0.3*rnd-0.8'
-new h 10 '0.3*rnd+0.5'
-subplot 1 1 0 '':title 'OHLC plot':box:ohlc o h l c
-
new x 100 'sin(pi*x)'
-new y 100 'cos(pi*x)'
-new z 100 'sin(2*pi*x)'
-new c 100 'cos(2*pi*x)'
-
-subplot 4 3 0:rotate 40 60:box:plot x y z
-subplot 4 3 1:rotate 40 60:box:area x y z
-subplot 4 3 2:rotate 40 60:box:tens x y z c
-subplot 4 3 3:rotate 40 60:box:bars x y z
-subplot 4 3 4:rotate 40 60:box:stem x y z
-subplot 4 3 5:rotate 40 60:box:textmark x y z c*2 '\alpha'
-subplot 4 3 6:rotate 40 60:box:tube x y z c/10
-subplot 4 3 7:rotate 40 60:box:mark x y z c 's'
-subplot 4 3 8:box:error x y z/10 c/10
-subplot 4 3 9:rotate 40 60:box:step x y z
-subplot 4 3 10:rotate 40 60:box:torus x z 'z';light on
-subplot 4 3 11:rotate 40 60:box:label x y z '%z'
-
new x 100 100 'sin(pi*(x+y)/2)*cos(pi*y/2)'
-new y 100 100 'cos(pi*(x+y)/2)*cos(pi*y/2)'
-new z 100 100 'sin(pi*y/2)'
-new c 100 100 'cos(pi*x)'
-
-subplot 4 4 0:rotate 40 60:box:surf x y z
-subplot 4 4 1:rotate 40 60:box:surfc x y z c
-subplot 4 4 2:rotate 40 60:box:surfa x y z c;alpha 1
-subplot 4 4 3:rotate 40 60:box:mesh x y z;meshnum 10
-subplot 4 4 4:rotate 40 60:box:tile x y z;meshnum 10
-subplot 4 4 5:rotate 40 60:box:tiles x y z c;meshnum 10
-subplot 4 4 6:rotate 40 60:box:axial x y z;alpha 0.5;light on
-subplot 4 4 7:rotate 40 60:box:cont x y z
-subplot 4 4 8:rotate 40 60:box:contf x y z;light on:contv x y z;light on
-subplot 4 4 9:rotate 40 60:box:belt x y z 'x';meshnum 10;light on
-subplot 4 4 10:rotate 40 60:box:dens x y z;alpha 0.5
-subplot 4 4 11:rotate 40 60:box
-fall x y z 'g';meshnum 10:fall x y z 'rx';meshnum 10
-subplot 4 4 12:rotate 40 60:box:belt x y z '';meshnum 10;light on
-subplot 4 4 13:rotate 40 60:box:boxs x y z '';meshnum 10;light on
-subplot 4 4 14:rotate 40 60:box:boxs x y z '#';meshnum 10;light on
-subplot 4 4 15:rotate 40 60:box:boxs x y z '@';meshnum 10;light on
-
new x 50 50 50 '(x+2)/3*sin(pi*y/2)'
-new y 50 50 50 '(x+2)/3*cos(pi*y/2)'
-new z 50 50 50 'z'
-new c 50 50 50 '-2*(x^2+y^2+z^4-z^2)+0.2'
-new d 50 50 50 '1-2*tanh(2*(x+y)^2)'
-
-alpha on:light on
-subplot 4 3 0:rotate 40 60:box:surf3 x y z c
-subplot 4 3 1:rotate 40 60:box:surf3c x y z c d
-subplot 4 3 2:rotate 40 60:box:surf3a x y z c d
-subplot 4 3 3:rotate 40 60:box:cloud x y z c
-subplot 4 3 4:rotate 40 60:box:cont3 x y z c:cont3 x y z c 'x':cont3 x y z c 'z'
-subplot 4 3 5:rotate 40 60:box:contf3 x y z c:contf3 x y z c 'x':contf3 x y z c 'z'
-subplot 4 3 6:rotate 40 60:box:dens3 x y z c:dens3 x y z c 'x':dens3 x y z c 'z'
-subplot 4 3 7:rotate 40 60:box:dots x y z c;meshnum 15
-subplot 4 3 8:rotate 40 60:box:densx c '' 0:densy c '' 0:densz c '' 0
-subplot 4 3 9:rotate 40 60:box:contx c '' 0:conty c '' 0:contz c '' 0
-subplot 4 3 10:rotate 40 60:box:contfx c '' 0:contfy c '' 0:contfz c '' 0
-
new x 20 20 20 '(x+2)/3*sin(pi*y/2)'
-new y 20 20 20 '(x+2)/3*cos(pi*y/2)'
-new z 20 20 20 'z+x'
-new ex 20 20 20 'x'
-new ey 20 20 20 'x^2+y'
-new ez 20 20 20 'y^2+z'
-
-new x1 50 50 '(x+2)/3*sin(pi*y/2)'
-new y1 50 50 '(x+2)/3*cos(pi*y/2)'
-new e1 50 50 'x'
-new e2 50 50 'x^2+y'
-
-subplot 3 3 0:rotate 40 60:box:vect x1 y1 e1 e2
-subplot 3 3 1:rotate 40 60:box:flow x1 y1 e1 e2
-subplot 3 3 2:rotate 40 60:box:pipe x1 y1 e1 e2
-subplot 3 3 3:rotate 40 60:box:dew x1 y1 e1 e2
-subplot 3 3 4:rotate 40 60:box:vect x y z ex ey ez
-subplot 3 3 5:rotate 40 60:box
-vect3 x y z ex ey ez:vect3 x y z ex ey ez 'x':vect3 x y z ex ey ez 'z'
-grid3 x y z z '{r9}':grid3 x y z z '{g9}x':grid3 x y z z '{b9}z'
-subplot 3 3 6:rotate 40 60:box:flow x y z ex ey ez
-subplot 3 3 7:rotate 40 60:box:pipe x y z ex ey ez
-
new re 128 'exp(-48*(x+0.7)^2)':new im 128
-pde a 'p^2+q^2-x-1+i*0.5*(z+x)*(z>-x)' re im 0.01 30
-transpose a
-subplot 1 1 0 '<_':title 'PDE solver'
-axis:xlabel '\i x':ylabel '\i z'
-crange 0 1:dens a 'wyrRk'
-fplot '-x' 'k|'
-text 0 0.95 'Equation: ik_0\partial_zu + \Delta u + x\cdot u + i \frac{x+z}{2}\cdot u = 0\n{}absorption: (x+z)/2 for x+z>0'
-
Function pipe is similar to flow but draw pipes (tubes) which radius is proportional to the amplitude of vector field. The color scheme is used for coloring (see Color scheme). At this warm color corresponds to normal flow (like attractor), cold one corresponds to inverse flow (like source).
-
-
MGL code:
-
call 'prepare2v'
-call 'prepare3v'
-subplot 2 2 0 '':title 'Pipe plot (default)':light on:box:pipe a b
-subplot 2 2 1 '':title '"i" style':box:pipe a b 'i'
-subplot 2 2 2 '':title 'from edges only':box:pipe a b '#'
-subplot 2 2 3:title '3d variant':rotate 50 60:box:pipe ex ey ez '' 0.1
-
Function plot is most standard way to visualize 1D data array. By default, Plot use colors from palette. However, you can specify manual color/palette, and even set to use new color for each points by using `!` style. Another feature is `` style which draw only markers without line between points.
-
Function pmap draw Poincare map - show intersections of the curve and the surface.
-
-
MGL code:
-
subplot 1 1 0 '<_^':title 'Poincare map sample'
-ode r 'cos(y)+sin(z);cos(z)+sin(x);cos(x)+sin(y)' 'xyz' [0.1,0,0] 0.1 100
-rotate 40 60:copy x r(0):copy y r(1):copy z r(2)
-ranges x y z
-axis:plot x y z 'b'
-xlabel '\i x' 0:ylabel '\i y' 0:zlabel '\i z'
-pmap x y z z 'b#o'
-fsurf '0'
-
ranges 0 1 0 1 0 1
-new x 50 '0.25*(1+cos(2*pi*x))'
-new y 50 '0.25*(1+sin(2*pi*x))'
-new z 50 'x'
-new a 20 30 '30*x*y*(1-x-y)^2*(x+y<1)'
-new rx 10 'rnd':new ry 10:fill ry '(1-v)*rnd' rx
-light on
-
-title 'Projection sample':ternary 4:rotate 50 60
-box:axis:grid
-plot x y z 'r2':surf a '#'
-xlabel 'X':ylabel 'Y':zlabel 'Z'
-
The radar plot is variant of plot, which make plot in polar coordinates and draw radial rays in point directions. If you just need a plot in polar coordinates then I recommend to use Curvilinear coordinates or plot in parametric form with x=r*cos(fi); y=r*sin(fi);.
-
-
MGL code:
-
new yr 10 3 '0.4*sin(pi*(x+1.5+y/2)+0.1*rnd)'
-subplot 1 1 0 '':title 'Radar plot (with grid, "\#")':radar yr '#'
-
new x 10 '0.5+rnd':cumsum x 'x':norm x -1 1
-copy y sin(pi*x)/1.5
-subplot 2 2 0 '<_':title 'Refill sample'
-box:axis:plot x y 'o ':fplot 'sin(pi*x)/1.5' 'B:'
-new r 100:refill r x y:plot r 'r'
-
-subplot 2 2 1 '<_':title 'Global spline'
-box:axis:plot x y 'o ':fplot 'sin(pi*x)/1.5' 'B:'
-new r 100:gspline r x y:plot r 'r'
-
-new y 10 '0.5+rnd':cumsum y 'x':norm y -1 1
-copy xx x:extend xx 10
-copy yy y:extend yy 10:transpose yy
-copy z sin(pi*xx*yy)/1.5
-alpha on:light on
-subplot 2 2 2:title '2d regular':rotate 40 60
-box:axis:mesh xx yy z 'k'
-new rr 100 100:refill rr x y z:surf rr
-
-new xx 10 10 '(x+1)/2*cos(y*pi/2-1)':new yy 10 10 '(x+1)/2*sin(y*pi/2-1)'
-copy z sin(pi*xx*yy)/1.5
-subplot 2 2 3:title '2d non-regular':rotate 40 60
-box:axis:plot xx yy z 'ko '
-new rr 100 100:refill rr xx yy z:surf rr
-
Function region fill the area between 2 curves. It support gradient filling if 2 colors per curve is specified. Also it can fill only the region y1<y<y2 if style `i` is used.
-
zrange 0 1
-new x 20 30 '(x+2)/3*cos(pi*y)'
-new y 20 30 '(x+2)/3*sin(pi*y)'
-new z 20 30 'exp(-6*x^2-2*sin(pi*y)^2)'
-
-subplot 2 1 0:title 'Cartesian space':rotate 30 -40
-axis 'xyzU':box
-xlabel 'x':ylabel 'y'
-origin 1 1:grid 'xy'
-mesh x y z
-
-# section along 'x' direction
-solve u x 0.5 'x'
-var v u.nx 0 1
-evaluate yy y u v
-evaluate xx x u v
-evaluate zz z u v
-plot xx yy zz 'k2o'
-
-# 1st section along 'y' direction
-solve u1 x -0.5 'y'
-var v1 u1.nx 0 1
-evaluate yy y v1 u1
-evaluate xx x v1 u1
-evaluate zz z v1 u1
-plot xx yy zz 'b2^'
-
-# 2nd section along 'y' direction
-solve u2 x -0.5 'y' u1
-evaluate yy y v1 u2
-evaluate xx x v1 u2
-evaluate zz z v1 u2
-plot xx yy zz 'r2v'
-
-subplot 2 1 1:title 'Accompanied space'
-ranges 0 1 0 1:origin 0 0
-axis:box:xlabel 'i':ylabel 'j':grid2 z 'h'
-
-plot u v 'k2o':line 0.4 0.5 0.8 0.5 'kA'
-plot v1 u1 'b2^':line 0.5 0.15 0.5 0.3 'bA'
-plot v1 u2 'r2v':line 0.5 0.7 0.5 0.85 'rA'
-
Function surf is most standard way to visualize 2D data array. Surf use color scheme for coloring (see Color scheme). You can use `#` style for drawing black meshes on the surface.
-
-
MGL code:
-
call 'prepare2d'
-subplot 2 2 0:title 'Surf plot (default)':rotate 50 60:light on:box:surf a
-subplot 2 2 1:title '"\#" style; meshnum 10':rotate 50 60:box:surf a '#'; meshnum 10
-subplot 2 2 2:title '"." style':rotate 50 60:box:surf a '.'
-new x 50 40 '0.8*sin(pi*x)*sin(pi*(y+1)/2)'
-new y 50 40 '0.8*cos(pi*x)*sin(pi*(y+1)/2)'
-new z 50 40 '0.8*cos(pi*(y+1)/2)'
-subplot 2 2 3:title 'parametric form':rotate 50 60:box:surf x y z 'BbwrR'
-
Function surf3 is one of most suitable (for my opinion) functions to visualize 3D data. It draw the isosurface(s) - surface(s) of constant amplitude (3D analogue of contour lines). You can draw wired isosurfaces if specify `#` style.
-
-
MGL code:
-
call 'prepare3d'
-light on:alpha on
-subplot 2 2 0:title 'Surf3 plot (default)'
-rotate 50 60:box:surf3 c
-subplot 2 2 1:title '"\#" style'
-rotate 50 60:box:surf3 c '#'
-subplot 2 2 2:title '"." style'
-rotate 50 60:box:surf3 c '.'
-
call 'prepare1d'
-subplot 1 3 0 '':box:plot y(:,0)
-text y 'This is very very long string drawn along a curve' 'k'
-text y 'Another string drawn under a curve' 'Tr'
-subplot 1 3 1 '':box:plot y(:,0)
-text y 'This is very very long string drawn along a curve' 'k:C'
-text y 'Another string drawn under a curve' 'Tr:C'
-subplot 1 3 2 '':box:plot y(:,0)
-text y 'This is very very long string drawn along a curve' 'k:R'
-text y 'Another string drawn under a curve' 'Tr:R'
-
Example of use triangulate for arbitrary placed points.
-
-
MGL code:
-
new x 100 '2*rnd-1':new y 100 '2*rnd-1':copy z x^2-y^2
-new g 30 30:triangulate d x y
-title 'Triangulation'
-rotate 50 60:box:light on
-triplot d x y z:triplot d x y z '#k'
-datagrid g x y z:mesh g 'm'
-
Functions triplot and quadplot draw set of triangles (or quadrangles, correspondingly) for irregular data arrays. Note, that you have to provide not only vertexes, but also the indexes of triangles or quadrangles. I.e. perform triangulation by some other library. See also triangulate.
-
Function vect is most standard way to visualize vector fields - it draw a lot of arrows or hachures for each data cell. It have a lot of options which can be seen on the figure (and in the sample code), and use color scheme for coloring (see Color scheme).
-
-
MGL code:
-
call 'prepare2v'
-call 'prepare3v'
-subplot 3 2 0 '':title 'Vect plot (default)':box:vect a b
-subplot 3 2 1 '':title '"." style; "=" style':box:vect a b '.='
-subplot 3 2 2 '':title '"f" style':box:vect a b 'f'
-subplot 3 2 3 '':title '">" style':box:vect a b '>'
-subplot 3 2 4 '':title '"<" style':box:vect a b '<'
-subplot 3 2 5:title '3d variant':rotate 50 60:box:vect ex ey ez
-
Function vect3 draw ordinary vector field plot but at slices of 3D data.
-
-
MGL code:
-
call 'prepare3v'
-subplot 2 1 0:title 'Vect3 sample':rotate 50 60
-origin 0 0 0:box:axis '_xyz'
-vect3 ex ey ez 'x':vect3 ex ey ez:vect3 ex ey ez 'z'
-subplot 2 1 1:title '"f" style':rotate 50 60
-origin 0 0 0:box:axis '_xyz'
-vect3 ex ey ez 'fx':vect3 ex ey ez 'f':vect3 ex ey ez 'fz'
-grid3 ex 'Wx':grid3 ex 'W':grid3 ex 'Wz'
-
list x -0.3 0 0.3:list y 0.3 -0.3 0.3:list e 0.7 0.7 0.7
-subplot 1 1 0:title 'Venn-like diagram'
-transptype 1:alpha on:error x y e e '!rgb@#o';alpha 0.1
-
This appendix contain the full list of symbols (characters) used by MathGL for setting up plot. Also it contain sections for full list of hot-keys supported by mglview tool and by UDAV program.
-
Create new window with empty script. Note, all scripts share variables. So, second window can be used to see some additional information of existed variables.
-
Ctrl-O
Open and execute/show script or data from file. You may switch off automatic exection in UDAV properties
-
Ctrl-S
Save script to a file.
-
Ctrl-P
Open printer dialog and print graphics.
-
Ctrl-Z
Undo changes in script editor.
-
Ctrl-Shift-Z
Redo changes in script editor.
-
Ctrl-X
Cut selected text into clipboard.
-
Ctrl-C
Copy selected text into clipboard.
-
Ctrl-V
Paste selected text from clipboard.
-
Ctrl-A
Select all text in editor.
-
Ctrl-F
Show dialog for text finding.
-
F3
Find next occurrence of the text.
-
Win-C or Meta-C
Show dialog for new command and put it into the script.
-
Win-F or Meta-F
Insert last fitted formula with found coefficients.
-
Win-S or Meta-S
Show dialog for styles and put it into the script. Styles define the plot view (color scheme, marks, dashing and so on).
-
Win-O or Meta-O
Show dialog for options and put it into the script. Options are used for additional setup the plot.
-
Win-N or Meta-N
Replace selected expression by its numerical value.
-
Win-P or Meta-P
Select file and insert its file name into the script.
-
Win-G or Meta-G
Show dialog for plot setup and put resulting code into the script. This dialog setup axis, labels, lighting and other general things.
-
Ctrl-Shift-O
Load data from file. Data will be deleted only at exit but UDAV will not ask to save it.
-
Ctrl-Shift-S
Save data to a file.
-
Ctrl-Shift-C
Copy range of numbers to clipboard.
-
Ctrl-Shift-V
Paste range of numbers from clipboard.
-
Ctrl-Shift-N
Recreate the data with new sizes and fill it by zeros.
-
Ctrl-Shift-R
Resize (interpolate) the data to specified sizes.
-
Ctrl-Shift-T
Transform data along dimension(s).
-
Ctrl-Shift-M
Make another data.
-
Ctrl-Shift-H
Find histogram of data.
-
Ctrl-T
Switch on/off transparency for the graphics.
-
Ctrl-L
Switch on/off additional lightning for the graphics.
-
Ctrl-G
Switch on/off grid of absolute coordinates.
-
Ctrl-Space
Restore default graphics rotation, zoom and perspective.
-
F5
Execute script and redraw graphics.
-
F6
Change canvas size to fill whole region.
-
F7
Stop script execution and drawing.
-
F8
Show/hide tool window with list of hidden plots.
-
F9
Restore status for `once` command and reload data.
-
Ctrl-F5
Run slideshow. If no parameter specified then the dialog with slideshow options will appear.
-
Ctrl-Comma, Ctrl-Period
Show next/previous slide. If no parameter specified then the dialog with slideshow options will appear.
-
Ctrl-W
Open dialog with slideshow options.
-
Ctrl-Shift-G
Copy graphics to clipboard.
-
F1
Show help on MGL commands
-
F2
Show/hide tool window with messages and information.
-
F4
Show/hide calculator which evaluate and help to type textual formulas. Textual formulas may contain data variables too.
The purpose of this License is to make a manual, textbook, or other
-functional and useful document free in the sense of freedom: to
-assure everyone the effective freedom to copy and redistribute it,
-with or without modifying it, either commercially or noncommercially.
-Secondarily, this License preserves for the author and publisher a way
-to get credit for their work, while not being considered responsible
-for modifications made by others.
-
-
This License is a kind of “copyleft”, which means that derivative
-works of the document must themselves be free in the same sense. It
-complements the GNU General Public License, which is a copyleft
-license designed for free software.
-
-
We have designed this License in order to use it for manuals for free
-software, because free software needs free documentation: a free
-program should come with manuals providing the same freedoms that the
-software does. But this License is not limited to software manuals;
-it can be used for any textual work, regardless of subject matter or
-whether it is published as a printed book. We recommend this License
-principally for works whose purpose is instruction or reference.
-
-
APPLICABILITY AND DEFINITIONS
-
-
This License applies to any manual or other work, in any medium, that
-contains a notice placed by the copyright holder saying it can be
-distributed under the terms of this License. Such a notice grants a
-world-wide, royalty-free license, unlimited in duration, to use that
-work under the conditions stated herein. The “Document”, below,
-refers to any such manual or work. Any member of the public is a
-licensee, and is addressed as “you”. You accept the license if you
-copy, modify or distribute the work in a way requiring permission
-under copyright law.
-
-
A “Modified Version” of the Document means any work containing the
-Document or a portion of it, either copied verbatim, or with
-modifications and/or translated into another language.
-
-
A “Secondary Section” is a named appendix or a front-matter section
-of the Document that deals exclusively with the relationship of the
-publishers or authors of the Document to the Document`s overall
-subject (or to related matters) and contains nothing that could fall
-directly within that overall subject. (Thus, if the Document is in
-part a textbook of mathematics, a Secondary Section may not explain
-any mathematics.) The relationship could be a matter of historical
-connection with the subject or with related matters, or of legal,
-commercial, philosophical, ethical or political position regarding
-them.
-
-
The “Invariant Sections” are certain Secondary Sections whose titles
-are designated, as being those of Invariant Sections, in the notice
-that says that the Document is released under this License. If a
-section does not fit the above definition of Secondary then it is not
-allowed to be designated as Invariant. The Document may contain zero
-Invariant Sections. If the Document does not identify any Invariant
-Sections then there are none.
-
-
The “Cover Texts” are certain short passages of text that are listed,
-as Front-Cover Texts or Back-Cover Texts, in the notice that says that
-the Document is released under this License. A Front-Cover Text may
-be at most 5 words, and a Back-Cover Text may be at most 25 words.
-
-
A “Transparent” copy of the Document means a machine-readable copy,
-represented in a format whose specification is available to the
-general public, that is suitable for revising the document
-straightforwardly with generic text editors or (for images composed of
-pixels) generic paint programs or (for drawings) some widely available
-drawing editor, and that is suitable for input to text formatters or
-for automatic translation to a variety of formats suitable for input
-to text formatters. A copy made in an otherwise Transparent file
-format whose markup, or absence of markup, has been arranged to thwart
-or discourage subsequent modification by readers is not Transparent.
-An image format is not Transparent if used for any substantial amount
-of text. A copy that is not “Transparent” is called “Opaque”.
-
-
Examples of suitable formats for Transparent copies include plain
-ASCII without markup, Texinfo input format, LaTeX input
-format, SGML or XML using a publicly available
-DTD, and standard-conforming simple HTML,
-PostScript or PDF designed for human modification. Examples
-of transparent image formats include PNG, XCF and
-JPG. Opaque formats include proprietary formats that can be
-read and edited only by proprietary word processors, SGML or
-XML for which the DTD and/or processing tools are
-not generally available, and the machine-generated HTML,
-PostScript or PDF produced by some word processors for
-output purposes only.
-
-
The “Title Page” means, for a printed book, the title page itself,
-plus such following pages as are needed to hold, legibly, the material
-this License requires to appear in the title page. For works in
-formats which do not have any title page as such, “Title Page” means
-the text near the most prominent appearance of the work`s title,
-preceding the beginning of the body of the text.
-
-
A section “Entitled XYZ” means a named subunit of the Document whose
-title either is precisely XYZ or contains XYZ in parentheses following
-text that translates XYZ in another language. (Here XYZ stands for a
-specific section name mentioned below, such as “Acknowledgements”,
-“Dedications”, “Endorsements”, or “History”.) To “Preserve the Title”
-of such a section when you modify the Document means that it remains a
-section “Entitled XYZ” according to this definition.
-
-
The Document may include Warranty Disclaimers next to the notice which
-states that this License applies to the Document. These Warranty
-Disclaimers are considered to be included by reference in this
-License, but only as regards disclaiming warranties: any other
-implication that these Warranty Disclaimers may have is void and has
-no effect on the meaning of this License.
-
-
VERBATIM COPYING
-
-
You may copy and distribute the Document in any medium, either
-commercially or noncommercially, provided that this License, the
-copyright notices, and the license notice saying this License applies
-to the Document are reproduced in all copies, and that you add no other
-conditions whatsoever to those of this License. You may not use
-technical measures to obstruct or control the reading or further
-copying of the copies you make or distribute. However, you may accept
-compensation in exchange for copies. If you distribute a large enough
-number of copies you must also follow the conditions in section 3.
-
-
You may also lend copies, under the same conditions stated above, and
-you may publicly display copies.
-
-
COPYING IN QUANTITY
-
-
If you publish printed copies (or copies in media that commonly have
-printed covers) of the Document, numbering more than 100, and the
-Document`s license notice requires Cover Texts, you must enclose the
-copies in covers that carry, clearly and legibly, all these Cover
-Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on
-the back cover. Both covers must also clearly and legibly identify
-you as the publisher of these copies. The front cover must present
-the full title with all words of the title equally prominent and
-visible. You may add other material on the covers in addition.
-Copying with changes limited to the covers, as long as they preserve
-the title of the Document and satisfy these conditions, can be treated
-as verbatim copying in other respects.
-
-
If the required texts for either cover are too voluminous to fit
-legibly, you should put the first ones listed (as many as fit
-reasonably) on the actual cover, and continue the rest onto adjacent
-pages.
-
-
If you publish or distribute Opaque copies of the Document numbering
-more than 100, you must either include a machine-readable Transparent
-copy along with each Opaque copy, or state in or with each Opaque copy
-a computer-network location from which the general network-using
-public has access to download using public-standard network protocols
-a complete Transparent copy of the Document, free of added material.
-If you use the latter option, you must take reasonably prudent steps,
-when you begin distribution of Opaque copies in quantity, to ensure
-that this Transparent copy will remain thus accessible at the stated
-location until at least one year after the last time you distribute an
-Opaque copy (directly or through your agents or retailers) of that
-edition to the public.
-
-
It is requested, but not required, that you contact the authors of the
-Document well before redistributing any large number of copies, to give
-them a chance to provide you with an updated version of the Document.
-
-
MODIFICATIONS
-
-
You may copy and distribute a Modified Version of the Document under
-the conditions of sections 2 and 3 above, provided that you release
-the Modified Version under precisely this License, with the Modified
-Version filling the role of the Document, thus licensing distribution
-and modification of the Modified Version to whoever possesses a copy
-of it. In addition, you must do these things in the Modified Version:
-
-
-
Use in the Title Page (and on the covers, if any) a title distinct
-from that of the Document, and from those of previous versions
-(which should, if there were any, be listed in the History section
-of the Document). You may use the same title as a previous version
-if the original publisher of that version gives permission.
-
-
List on the Title Page, as authors, one or more persons or entities
-responsible for authorship of the modifications in the Modified
-Version, together with at least five of the principal authors of the
-Document (all of its principal authors, if it has fewer than five),
-unless they release you from this requirement.
-
-
State on the Title page the name of the publisher of the
-Modified Version, as the publisher.
-
-
Preserve all the copyright notices of the Document.
-
-
Add an appropriate copyright notice for your modifications
-adjacent to the other copyright notices.
-
-
Include, immediately after the copyright notices, a license notice
-giving the public permission to use the Modified Version under the
-terms of this License, in the form shown in the Addendum below.
-
-
Preserve in that license notice the full lists of Invariant Sections
-and required Cover Texts given in the Document`s license notice.
-
-
Include an unaltered copy of this License.
-
-
Preserve the section Entitled “History”, Preserve its Title, and add
-to it an item stating at least the title, year, new authors, and
-publisher of the Modified Version as given on the Title Page. If
-there is no section Entitled “History” in the Document, create one
-stating the title, year, authors, and publisher of the Document as
-given on its Title Page, then add an item describing the Modified
-Version as stated in the previous sentence.
-
-
Preserve the network location, if any, given in the Document for
-public access to a Transparent copy of the Document, and likewise
-the network locations given in the Document for previous versions
-it was based on. These may be placed in the “History” section.
-You may omit a network location for a work that was published at
-least four years before the Document itself, or if the original
-publisher of the version it refers to gives permission.
-
-
For any section Entitled “Acknowledgements” or “Dedications”, Preserve
-the Title of the section, and preserve in the section all the
-substance and tone of each of the contributor acknowledgements and/or
-dedications given therein.
-
-
Preserve all the Invariant Sections of the Document,
-unaltered in their text and in their titles. Section numbers
-or the equivalent are not considered part of the section titles.
-
-
Delete any section Entitled “Endorsements”. Such a section
-may not be included in the Modified Version.
-
-
Do not retitle any existing section to be Entitled “Endorsements” or
-to conflict in title with any Invariant Section.
-
-
Preserve any Warranty Disclaimers.
-
-
-
If the Modified Version includes new front-matter sections or
-appendices that qualify as Secondary Sections and contain no material
-copied from the Document, you may at your option designate some or all
-of these sections as invariant. To do this, add their titles to the
-list of Invariant Sections in the Modified Version`s license notice.
-These titles must be distinct from any other section titles.
-
-
You may add a section Entitled “Endorsements”, provided it contains
-nothing but endorsements of your Modified Version by various
-parties—for example, statements of peer review or that the text has
-been approved by an organization as the authoritative definition of a
-standard.
-
-
You may add a passage of up to five words as a Front-Cover Text, and a
-passage of up to 25 words as a Back-Cover Text, to the end of the list
-of Cover Texts in the Modified Version. Only one passage of
-Front-Cover Text and one of Back-Cover Text may be added by (or
-through arrangements made by) any one entity. If the Document already
-includes a cover text for the same cover, previously added by you or
-by arrangement made by the same entity you are acting on behalf of,
-you may not add another; but you may replace the old one, on explicit
-permission from the previous publisher that added the old one.
-
-
The author(s) and publisher(s) of the Document do not by this License
-give permission to use their names for publicity for or to assert or
-imply endorsement of any Modified Version.
-
-
COMBINING DOCUMENTS
-
-
You may combine the Document with other documents released under this
-License, under the terms defined in section 4 above for modified
-versions, provided that you include in the combination all of the
-Invariant Sections of all of the original documents, unmodified, and
-list them all as Invariant Sections of your combined work in its
-license notice, and that you preserve all their Warranty Disclaimers.
-
-
The combined work need only contain one copy of this License, and
-multiple identical Invariant Sections may be replaced with a single
-copy. If there are multiple Invariant Sections with the same name but
-different contents, make the title of each such section unique by
-adding at the end of it, in parentheses, the name of the original
-author or publisher of that section if known, or else a unique number.
-Make the same adjustment to the section titles in the list of
-Invariant Sections in the license notice of the combined work.
-
-
In the combination, you must combine any sections Entitled “History”
-in the various original documents, forming one section Entitled
-“History”; likewise combine any sections Entitled “Acknowledgements”,
-and any sections Entitled “Dedications”. You must delete all
-sections Entitled “Endorsements.”
-
-
COLLECTIONS OF DOCUMENTS
-
-
You may make a collection consisting of the Document and other documents
-released under this License, and replace the individual copies of this
-License in the various documents with a single copy that is included in
-the collection, provided that you follow the rules of this License for
-verbatim copying of each of the documents in all other respects.
-
-
You may extract a single document from such a collection, and distribute
-it individually under this License, provided you insert a copy of this
-License into the extracted document, and follow this License in all
-other respects regarding verbatim copying of that document.
-
-
AGGREGATION WITH INDEPENDENT WORKS
-
-
A compilation of the Document or its derivatives with other separate
-and independent documents or works, in or on a volume of a storage or
-distribution medium, is called an “aggregate” if the copyright
-resulting from the compilation is not used to limit the legal rights
-of the compilation`s users beyond what the individual works permit.
-When the Document is included in an aggregate, this License does not
-apply to the other works in the aggregate which are not themselves
-derivative works of the Document.
-
-
If the Cover Text requirement of section 3 is applicable to these
-copies of the Document, then if the Document is less than one half of
-the entire aggregate, the Document`s Cover Texts may be placed on
-covers that bracket the Document within the aggregate, or the
-electronic equivalent of covers if the Document is in electronic form.
-Otherwise they must appear on printed covers that bracket the whole
-aggregate.
-
-
TRANSLATION
-
-
Translation is considered a kind of modification, so you may
-distribute translations of the Document under the terms of section 4.
-Replacing Invariant Sections with translations requires special
-permission from their copyright holders, but you may include
-translations of some or all Invariant Sections in addition to the
-original versions of these Invariant Sections. You may include a
-translation of this License, and all the license notices in the
-Document, and any Warranty Disclaimers, provided that you also include
-the original English version of this License and the original versions
-of those notices and disclaimers. In case of a disagreement between
-the translation and the original version of this License or a notice
-or disclaimer, the original version will prevail.
-
-
If a section in the Document is Entitled “Acknowledgements”,
-“Dedications”, or “History”, the requirement (section 4) to Preserve
-its Title (section 1) will typically require changing the actual
-title.
-
-
TERMINATION
-
-
You may not copy, modify, sublicense, or distribute the Document except
-as expressly provided for under this License. Any other attempt to
-copy, modify, sublicense or distribute the Document is void, and will
-automatically terminate your rights under this License. However,
-parties who have received copies, or rights, from you under this
-License will not have their licenses terminated so long as such
-parties remain in full compliance.
-
-
FUTURE REVISIONS OF THIS LICENSE
-
-
The Free Software Foundation may publish new, revised versions
-of the GNU Free Documentation License from time to time. Such new
-versions will be similar in spirit to the present version, but may
-differ in detail to address new problems or concerns. See
-http://www.gnu.org/copyleft/.
-
-
Each version of the License is given a distinguishing version number.
-If the Document specifies that a particular numbered version of this
-License “or any later version” applies to it, you have the option of
-following the terms and conditions either of that specified version or
-of any later version that has been published (not as a draft) by the
-Free Software Foundation. If the Document does not specify a version
-number of this License, you may choose any version ever published (not
-as a draft) by the Free Software Foundation.
-
-
-
-
ADDENDUM: How to use this License for your documents
-
-
To use this License in a document you have written, include a copy of
-the License in the document and put the following copyright and
-license notices just after the title page:
-
-
-
Copyright (C) yearyour name.
- Permission is granted to copy, distribute and/or modify this document
- under the terms of the GNU Free Documentation License, Version 1.2
- or any later version published by the Free Software Foundation;
- with no Invariant Sections, no Front-Cover Texts, and no Back-Cover
- Texts. A copy of the license is included in the section entitled ``GNU
- Free Documentation License''.
-
-
-
If you have Invariant Sections, Front-Cover Texts and Back-Cover Texts,
-replace the “with…Texts.” line with this:
-
-
-
with the Invariant Sections being list their titles, with
- the Front-Cover Texts being list, and with the Back-Cover Texts
- being list.
-
-
-
If you have Invariant Sections without Cover Texts, or some other
-combination of the three, merge those two alternatives to suit the
-situation.
-
-
If your document contains nontrivial examples of program code, we
-recommend releasing these examples in parallel under your choice of
-free software license, such as the GNU General Public License,
-to permit their use in free software.
-
Permission is granted to copy, distribute and/or modify this document
-under the terms of the GNU Free Documentation License, Version 1.2
-or any later version published by the Free Software Foundation;
-with no Invariant Sections, no Front-Cover Texts, and no Back-Cover
-Texts. A copy of the license is included in the section entitled “GNU
-Free Documentation License.”
-
There are number of special comments for MGL script, which set some global behavior (like, animation, dialog for parameters and so on). All these special comments starts with double sign ##. Let consider them.
-
-
-
`##cv1 v2 [dv=1]`
-
Sets the parameter for animation loop relative to variable $0. Here v1 and v2 are initial and final values, dv is the increment.
-
-
-
`##a val`
-
Adds the parameter val to the list of animation relative to variable $0. You can use it several times (one parameter per line) or combine it with animation loop ##c.
-
-
-
`##d $I kind|label|par1|par2|...`
-
Creates custom dialog for changing plot properties. Each line adds one widget to the dialog. Here $I is id ($0,$1...$9,$a,$b...$z), label is the label of widget, kind is the kind of the widget:
-
-
`e` for editor or input line (parameter is initial value) ,
-
`v` for spinner or counter (parameters are "ini|min|max|step|big_step"),
-
`s` for slider (parameters are "ini|min|max|step"),
-
`b` for check box (parameter is "ini"; also understand "on"=1),
-
`c` for choice (parameters are possible choices).
-
-
Now, it work in FLTK-based mgllab and mglview only.
-
There is LaTeX package mgltex (was made by Diego Sejas Viscarra) which allow one to make figures directly from MGL script located in LaTeX file.
-
-
For using this package you need to specify --shell-escape option for latex/pdflatex or manually run mglconv tool with produced MGL scripts for generation of images. Don`t forgot to run latex/pdflatex second time to insert generated images into the output document. Also you need to run pdflatex third time to update converted from EPS images if you are using vector EPS output (default).
-
-
The package may have following options: draft, final — the same as in the graphicx package; on, off — to activate/deactivate the creation of scripts and graphics; comments, nocomments — to make visible/invisible comments contained inside mglcomment environments; jpg, jpeg, png — to export graphics as JPEG/PNG images; eps, epsz — to export to uncompressed/compressed EPS format as primitives; bps, bpsz — to export to uncompressed/compressed EPS format as bitmap (doesn`t work with pdflatex); pdf — to export to 3D PDF; tex — to export to LaTeX/tikz document.
-
-
The package defines the following environments:
-
-
`mgl`
-
It writes its contents to a general script which has the same name as the LaTeX document, but its extension is .mgl. The code in this environment is compiled and the image produced is included. It takes exactly the same optional arguments as the \includegraphics command, plus an additional argument imgext, which specifies the extension to save the image.
-
-
An example of usage of `mgl` environment would be:
-
\begin{mglfunc}{prepare2d}
- new a 50 40 '0.6*sin(pi*(x+1))*sin(1.5*pi*(y+1))+0.4*cos(0.75*pi*(x+1)*(y+1))'
- new b 50 40 '0.6*cos(pi*(x+1))*cos(1.5*pi*(y+1))+0.4*cos(0.75*pi*(x+1)*(y+1))'
-\end{mglfunc}
-
-\begin{figure}[!ht]
- \centering
- \begin{mgl}[width=0.85\textwidth,height=7.5cm]
- fog 0.5
- call 'prepare2d'
- subplot 2 2 0 : title 'Surf plot (default)' : rotate 50 60 : light on : box : surf a
-
- subplot 2 2 1 : title '"\#" style; meshnum 10' : rotate 50 60 : box
- surf a '#'; meshnum 10
-
- subplot 2 2 2 : title 'Mesh plot' : rotate 50 60 : box
- mesh a
-
- new x 50 40 '0.8*sin(pi*x)*sin(pi*(y+1)/2)'
- new y 50 40 '0.8*cos(pi*x)*sin(pi*(y+1)/2)'
- new z 50 40 '0.8*cos(pi*(y+1)/2)'
- subplot 2 2 3 : title 'parametric form' : rotate 50 60 : box
- surf x y z 'BbwrR'
- \end{mgl}
-\end{figure}
-
-
-
`mgladdon`
-
It adds its contents to the general script, without producing any image.
-
-
`mglcode`
-
Is exactly the same as `mgl`, but it writes its contents verbatim to its own file, whose name is specified as a mandatory argument.
-
-
`mglscript`
-
Is exactly the same as `mglcode`, but it doesn`t produce any image, nor accepts optional arguments. It is useful, for example, to create a MGL script, which can later be post processed by another package like "listings".
-
-
`mglblock`
-
It writes its contents verbatim to a file, specified as a mandatory argument, and to the LaTeX document, and numerates each line of code.
-
-
-
`mglverbatim`
-
Exactly the same as `mglblock`, but it doesn`t write to a file. This environment doesn`t have arguments.
-
-
`mglfunc`
-
Is used to define MGL functions. It takes one mandatory argument, which is the name of the function, plus one additional argument, which specifies the number of arguments of the function. The environment needs to contain only the body of the function, since the first and last lines are appended automatically, and the resulting code is written at the end of the general script, after the stop command, which is also written automatically. The warning is produced if 2 or more function with the same name is defined.
-
-
`mglcomment`
-
Is used to contain multiline comments. This comments will be visible/invisible in the output document, depending on the use of the package options comments and nocomments (see above), or the \mglcomments and \mglnocomments commands (see bellow).
-
-
`mglsetup`
-
If many scripts with the same code are to be written, the repetitive code can be written inside this environment only once, then this code will be used automatically every time the `\mglplot` command is used (see below). It takes one optional argument, which is a name to be associated to the corresponding contents of the environment; this name can be passed to the `\mglplot` command to use the corresponding block of code automatically (see below).
-
-
-
-
The package also defines the following commands:
-
-
`\mglplot`
-
It takes one mandatory argument, which is MGL instructions separated by the symbol `:` this argument can be more than one line long. It takes the same optional arguments as the `mgl` environment, plus an additional argument setup, which indicates the name associated to a block of code inside a `mglsetup` environment. The code inside the mandatory argument will be appended to the block of code specified, and the resulting code will be written to the general script.
-
-
An example of usage of `\mglplot` command would be:
-
This command takes the same optional arguments as the `mgl` environment, and one mandatory argument, which is the name of a MGL script. This command will compile the corresponding script and include the resulting image. It is useful when you have a script outside the LaTeX document, and you want to include the image, but you don`t want to type the script again.
-
-
`\mglinclude`
-
This is like `\mglgraphics` but, instead of creating/including the corresponding image, it writes the contents of the MGL script to the LaTeX document, and numerates the lines.
-
-
`\mgldir`
-
This command can be used in the preamble of the document to specify a directory where LaTeX will save the MGL scripts and generate the corresponding images. This directory is also where `\mglgraphics` and `\mglinclude` will look for scripts.
-
-
`\mglquality`
-
Adjust the quality of the MGL graphics produced similarly to quality.
-
-
`\mgltexon, \mgltexoff`
-
Activate/deactivate the creation of MGL scripts and images. Notice these commands have local behavior in the sense that their effect is from the point they are called on.
-
-
`\mglcomment, \mglnocomment`
-
Make visible/invisible the contents of the mglcomment environments. These commands have local effect too.
-
-
`\mglTeX`
-
It just pretty prints the name of the package.
-
-
-
-
As an additional feature, when an image is not found or cannot be included, instead of issuing an error, mgltex prints a box with the word `MGL image not found` in the LaTeX document.
-
Draw bitmap (logo) along whole axis range, which can be changed by Command options. Bitmap can be loaded from file or specified as RGBA values for pixels. Parameter smooth set to draw bitmap without or with color interpolation.
-
-
-
-
-
-
Ðоманда MGL: symbolx y 'id' ['fnt'='' size=-1]
-
Ðоманда MGL: symbolx y z 'id' ['fnt'='' size=-1]
The function draws flow threads for the 3D vector field {ax, ay, az} parametrically depending on coordinates x, y, z. Flow threads starts from given plane. Option value set the approximate number of threads (default is 5). String sch may contain:
-
-
color scheme - up-half (warm) corresponds to normal flow (like attractor), bottom-half (cold) corresponds to inverse flow (like source);
-
`x`, `z` for normal of starting plane (default is y-direction);
-
`v` for drawing arrows on the threads;
-
`t` for drawing tapes of normals in x-y and y-z planes.
-
-
See also flow, pipe, vect. См. flow3 sample, Ð´Ð»Ñ Ð¿ÑимеÑов кода и гÑаÑика.
-
These functions change the data in some direction like differentiations, integrations and so on. The direction in which the change will applied is specified by the string parameter, which may contain `x`, `y` or `z` characters for 1-st, 2-nd and 3-d dimension correspondingly.
-
This chapter contain information about basic and advanced MathGL, hints and samples for all types of graphics. I recommend you read first 2 sections one after another and at least look on Hints section. Also I recommend you to look at General concepts and FAQ.
-
MGL script can be used by several manners. Each has positive and negative sides:
-
-
Using UDAV.
-
-
Positive sides are possibilities to view the plot at once and to modify it, rotate, zoom or switch on transparency or lighting by hands or by mouse. Negative side is the needness of the X-terminal.
-
Using command line tools.
-
-
Positive aspects are: batch processing of similar data set, for example, a set of resulting data files for different calculation parameters), running from the console program, including the cluster calculation), fast and automated drawing, saving pictures for further analysis, or demonstration). Negative sides are: the usage of the external program for picture viewing. Also, the data plotting is non-visual. So, you have to imagine the picture, view angles, lighting and so on) before the plotting. I recommend to use graphical window for determining the optimal parameters of plotting on the base of some typical data set. And later use these parameters for batch processing in console program.
-
-
In this case you can use the program: mglconv or mglview for viewing.
-
-
Using C/C++/... code.
-
-
You can easily execute MGL script within C/C++/Fortan code. This can be useful for fast data plotting, for example, in web applications, where textual string (MGL script) may contain all necessary information for plot. The basic C++ code may look as following
-
const char *mgl_script; // script itself, can be of type const wchar_t*
-mglGraph gr;
-mglParse pr;
-pr.Execute(&gr, mgl_script);
-
-
-
The simplest script is
-
box # draw bounding box
-axis # draw axis
-fplot 'x^3' # draw some function
-
-
Just type it in UDAV and press F5. Also you can save it in text file `test.mgl` and type in the console mglconv test.mgl what produce file `test.mgl.png` with resulting picture.
-
Now I show several non-obvious features of MGL: several subplots in a single picture, curvilinear coordinates, text printing and so on. Generally you may miss this section at first reading, but I don`t recommend it.
-
Let me demonstrate possibilities of plot positioning and rotation. MathGL has a set of functions: subplot, inplot, title, aspect and rotate and so on (see Subplots and rotation). The order of their calling is strictly determined. First, one changes the position of plot in image area (functions subplot, inplot and multiplot). Secondly, you can add the title of plot by title function. After that one may rotate the plot (command rotate). Finally, one may change aspects of axes (command aspect). The following code illustrates the aforesaid it:
-
Here I used function Puts for printing the text in arbitrary position of picture (see Text printing). Text coordinates and size are connected with axes. However, text coordinates may be everywhere, including the outside the bounding box. I`ll show its features later in Text features.
-
-
Note that several commands can be placed in a string if they are separated by `:` symbol.
-
-
-
-
More complicated sample show how to use most of positioning functions:
-
MathGL library can draw not only the bounding box but also the axes, grids, labels and so on. The ranges of axes and their origin (the point of intersection) are determined by functions SetRange(), SetRanges(), SetOrigin() (see Ranges (bounding box)). Ticks on axis are specified by function SetTicks, SetTicksVal, SetTicksTime (see Ticks). But usually
-
-
Command axis draws axes. Its textual string shows in which directions the axis or axes will be drawn (by default "xyz", function draws axes in all directions). Command grid draws grid perpendicularly to specified directions. Example of axes and grid drawing is:
-
Note, that MathGL can draw not only single axis (which is default). But also several axis on the plot (see right plots). The idea is that the change of settings does not influence on the already drawn graphics. So, for 2-axes I setup the first axis and draw everything concerning it. Then I setup the second axis and draw things for the second axis. Generally, the similar idea allows one to draw rather complicated plot of 4 axis with different ranges (see bottom left plot).
-
-
At this inverted axis can be created by 2 methods. First one is used in this sample - just specify minimal axis value to be large than maximal one. This method work well for 2D axis, but can wrongly place labels in 3D case. Second method is more general and work in 3D case too - just use aspect function with negative arguments. For example, following code will produce exactly the same result for 2D case, but 2nd variant will look better in 3D.
-
Another MathGL feature is fine ticks tunning. By default (if it is not changed by SetTicks function), MathGL try to adjust ticks positioning, so that they looks most human readable. At this, MathGL try to extract common factor for too large or too small axis ranges, as well as for too narrow ranges. Last one is non-common notation and can be disabled by SetTuneTicks function.
-
-
Also, one can specify its own ticks with arbitrary labels by help of SetTicksVal function. Or one can set ticks in time format. In last case MathGL will try to select optimal format for labels with automatic switching between years, months/days, hours/minutes/seconds or microseconds. However, you can specify its own time representation using formats described in http://www.manpagez.com/man/3/strftime/. Most common variants are `%X` for national representation of time, `%x` for national representation of date, `%Y` for year with century.
-
-
The sample code, demonstrated ticks feature is
-
subplot 3 3 0:title 'Usual axis'
-axis
-
-subplot 3 3 1:title 'Too big/small range'
-ranges -1000 1000 0 0.001:axis
-
-subplot 3 3 2:title 'LaTeX-like labels'
-axis 'F!'
-
-subplot 3 3 3:title 'Too narrow range'
-ranges 100 100.1 10 10.01:axis
-
-subplot 3 3 4:title 'No tuning, manual "+"'
-axis '+!'
-# for version <2.3 you can use
-#tuneticks off:axis
-
-subplot 3 3 5:title 'Template for ticks'
-xtick 'xxx:%g':ytick 'y:%g'
-axis
-
-xtick '':ytick '' # switch it off for other plots
-
-subplot 3 3 6:title 'No tuning, higher precision'
-axis '!4'
-
-subplot 3 3 7:title 'Manual ticks'
-ranges -pi pi 0 2
-xtick pi 3 '\pi'
-xtick 0.886 'x^*' on # note this will disable subticks drawing
-# or you can use
-#xtick -pi '\pi' -pi/2 '-\pi/2' 0 '0' 0.886 'x^*' pi/2 '\pi/2' pi 'pi'
-# or you can use
-#list v -pi -pi/2 0 0.886 pi/2 pi:xtick v '-\pi\n-\pi/2\n{}0\n{}x^*\n\pi/2\n\pi'
-axis:grid:fplot '2*cos(x^2)^2' 'r2'
-
-subplot 3 3 8:title 'Time ticks'
-xrange 0 3e5:ticktime 'x':axis
-
-
-
-
The last sample I want to show in this subsection is Log-axis. From MathGL`s point of view, the log-axis is particular case of general curvilinear coordinates. So, we need first define new coordinates (see also Curvilinear coordinates) by help of SetFunc or SetCoor functions. At this one should wary about proper axis range. So the code looks as following:
-
You can see that MathGL automatically switch to log-ticks as we define log-axis formula (in difference from v.1.*). Moreover, it switch to log-ticks for any formula if axis range will be large enough (see right bottom plot). Another interesting feature is that you not necessary define usual log-axis (i.e. when coordinates are positive), but you can define “minus-log” axis when coordinate is negative (see left bottom plot).
-
As I noted in previous subsection, MathGL support curvilinear coordinates. In difference from other plotting programs and libraries, MathGL uses textual formulas for connection of the old (data) and new (output) coordinates. This allows one to plot in arbitrary coordinates. The following code plots the line y=0, z=0 in Cartesian, polar, parabolic and spiral coordinates:
-
MathGL handle colorbar as special kind of axis. So, most of functions for axis and ticks setup will work for colorbar too. Colorbars can be in log-scale, and generally as arbitrary function scale; common factor of colorbar labels can be separated; and so on.
-
-
But of course, there are differences - colorbars usually located out of bounding box. At this, colorbars can be at subplot boundaries (by default), or at bounding box (if symbol `I` is specified). Colorbars can handle sharp colors. And they can be located at arbitrary position too. The sample code, which demonstrate colorbar features is:
-
call 'prepare2d'
-new v 9 'x'
-
-subplot 2 2 0:title 'Colorbar out of box':box
-colorbar '<':colorbar '>':colorbar '_':colorbar '^'
-
-subplot 2 2 1:title 'Colorbar near box':box
-colorbar '<I':colorbar '>I':colorbar '_I':colorbar '^I'
-
-subplot 2 2 2:title 'manual colors':box:contd v a
-colorbar v '<':colorbar v '>':colorbar v '_':colorbar v '^'
-
-subplot 2 2 3:title '':text -0.5 1.55 'Color positions' ':C' -2
-
-colorbar 'bwr>' 0.25 0:text -0.9 1.2 'Default'
-colorbar 'b{w,0.3}r>' 0.5 0:text -0.1 1.2 'Manual'
-
-crange 0.01 1e3
-colorbar '>' 0.75 0:text 0.65 1.2 'Normal scale'
-colorbar '>':text 1.35 1.2 'Log scale'
-
Box around the plot is rather useful thing because it allows one to: see the plot boundaries, and better estimate points position since box contain another set of ticks. MathGL provide special function for drawing such box - box function. By default, it draw black or white box with ticks (color depend on transparency type, see Types of transparency). However, you can change the color of box, or add drawing of rectangles at rear faces of box. Also you can disable ticks drawing, but I don`t know why anybody will want it. The sample code, which demonstrate box features is:
-
There are another unusual axis types which are supported by MathGL. These are ternary and quaternary axis. Ternary axis is special axis of 3 coordinates a, b, c which satisfy relation a+b+c=1. Correspondingly, quaternary axis is special axis of 4 coordinates a, b, c, d which satisfy relation a+b+c+d=1.
-
-
Generally speaking, only 2 of coordinates (3 for quaternary) are independent. So, MathGL just introduce some special transformation formulas which treat a as `x`, b as `y` (and c as `z` for quaternary). As result, all plotting functions (curves, surfaces, contours and so on) work as usual, but in new axis. You should use ternary function for switching to ternary/quaternary coordinates. The sample code is:
-
ranges 0 1 0 1 0 1
-new x 50 '0.25*(1+cos(2*pi*x))'
-new y 50 '0.25*(1+sin(2*pi*x))'
-new z 50 'x'
-new a 20 30 '30*x*y*(1-x-y)^2*(x+y<1)'
-new rx 10 'rnd':copy ry (1-rx)*rnd
-light on
-
-subplot 2 2 0:title 'Ordinary axis 3D':rotate 50 60
-box:axis:grid
-plot x y z 'r2':surf a '#'
-xlabel 'B':ylabel 'C':zlabel 'Z'
-
-subplot 2 2 1:title 'Ternary axis (x+y+t=1)':ternary 1
-box:axis:grid 'xyz' 'B;'
-plot x y 'r2':plot rx ry 'q^ ':cont a:line 0.5 0 0 0.75 'g2'
-xlabel 'B':ylabel 'C':tlabel 'A'
-
-subplot 2 2 2:title 'Quaternary axis 3D':rotate 50 60:ternary 2
-box:axis:grid 'xyz' 'B;'
-plot x y z 'r2':surf a '#'
-xlabel 'B':ylabel 'C':tlabel 'A':zlabel 'D'
-
-subplot 2 2 3:title 'Ternary axis 3D':rotate 50 60:ternary 1
-box:axis:grid 'xyz' 'B;'
-plot x y z 'r2':surf a '#'
-xlabel 'B':ylabel 'C':tlabel 'A':zlabel 'Z'
-
MathGL prints text by vector font. There are functions for manual specifying of text position (like Puts) and for its automatic selection (like Label, Legend and so on). MathGL prints text always in specified position even if it lies outside the bounding box. The default size of font is specified by functions SetFontSize* (see Font settings). However, the actual size of output string depends on subplot size (depends on functions SubPlot, InPlot). The switching of the font style (italic, bold, wire and so on) can be done for the whole string (by function parameter) or inside the string. By default MathGL parses TeX-like commands for symbols and indexes (see Font styles).
-
-
Text can be printed as usual one (from left to right), along some direction (rotated text), or along a curve. Text can be printed on several lines, divided by new line symbol `\n`.
-
-
Example of MathGL font drawing is:
-
call 'prepare1d'
-
-subplot 2 2 0 ''
-text 0 1 'Text can be in ASCII and in Unicode'
-text 0 0.6 'It can be \wire{wire}, \big{big} or #r{colored}'
-text 0 0.2 'One can change style in string: \b{bold}, \i{italic, \b{both}}'
-text 0 -0.2 'Easy to \a{overline} or \u{underline}'
-text 0 -0.6 'Easy to change indexes ^{up} _{down} @{center}'
-text 0 -1 'It parse TeX: \int \alpha \cdot \
-\sqrt3{sin(\pi x)^2 + \gamma_{i_k}} dx'
-
-subplot 2 2 1 ''
- text 0 0.5 '\sqrt{\frac{\alpha^{\gamma^2}+\overset 1{\big\infty}}{\sqrt3{2+b}}}' '@' -2
-text 0 -0.5 'Text can be printed\n{}on several lines'
-
-subplot 2 2 2 '':box:plot y(:,0)
-text y 'This is very very long string drawn along a curve' 'k'
-text y 'Another string drawn under a curve' 'Tr'
-
-subplot 2 2 3 '':line -1 -1 1 -1 'rA':text 0 -1 1 -1 'Horizontal'
-line -1 -1 1 1 'rA':text 0 0 1 1 'At angle' '@'
-line -1 -1 -1 1 'rA':text -1 0 -1 1 'Vertical'
-
-
-
-
You can change font faces by loading font files by function loadfont. Note, that this is long-run procedure. Font faces can be downloaded from MathGL website or from here. The sample code is:
-
Legend is one of standard ways to show plot annotations. Basically you need to connect the plot style (line style, marker and color) with some text. In MathGL, you can do it by 2 methods: manually using addlegend function; or use `legend` option (see Command options), which will use last plot style. In both cases, legend entries will be added into internal accumulator, which later used for legend drawing itself. clearlegend function allow you to remove all saved legend entries.
-
-
There are 2 features. If plot style is empty then text will be printed without indent. If you want to plot the text with indent but without plot sample then you need to use space `` as plot style. Such style `` will draw a plot sample (line with marker(s)) which is invisible line (i.e. nothing) and print the text with indent as usual one.
-
-
Command legend draw legend on the plot. The position of the legend can be selected automatic or manually. You can change the size and style of text labels, as well as setup the plot sample. The sample code demonstrating legend features is:
-
The last common thing which I want to show in this section is how one can cut off points from plot. There are 4 mechanism for that.
-
-
You can set one of coordinate to NAN value. All points with NAN values will be omitted.
-
-
You can enable cutting at edges by SetCut function. As result all points out of bounding box will be omitted.
-
-
You can set cutting box by SetCutBox function. All points inside this box will be omitted.
-
-
You can define cutting formula by SetCutOff function. All points for which the value of formula is nonzero will be omitted. Note, that this is the slowest variant.
-
-
-
Below I place the code which demonstrate last 3 possibilities:
-
Class mglData contains all functions for the data handling in MathGL (see Data processing). There are several matters why I use class mglData but not a single array: it does not depend on type of data (mreal or double), sizes of data arrays are kept with data, memory working is simpler and safer.
-
MathGL has functions for data processing: differentiating, integrating, smoothing and so on (for more detail, see Data processing). Let us consider some examples. The simplest ones are integration and differentiation. The direction in which operation will be performed is specified by textual string, which may contain symbols `x`, `y` or `z`. For example, the call of diff 'x' will differentiate data along `x` direction; the call of integrate 'xy' perform the double integration of data along `x` and `y` directions; the call of diff2 'xyz' will apply 3d Laplace operator to data and so on. Example of this operations on 2d array a=x*y is presented in code:
-
Data smoothing (command smooth) is more interesting and important. This function has single argument which define type of smoothing and its direction. Now 3 methods are supported: `3` - linear averaging by 3 points, `5` - linear averaging by 5 points, and default one - quadratic averaging by 5 points.
-
-
MathGL also have some amazing functions which is not so important for data processing as useful for data plotting. There are functions for finding envelope (useful for plotting rapidly oscillating data), for data sewing (useful to removing jumps on the phase), for data resizing (interpolation). Let me demonstrate it:
-
Finally one can create new data arrays on base of the existing one: extract slice, row or column of data (subdata), summarize along a direction(s) (sum), find distribution of data elements (hist) and so on.
-
-
Another interesting feature of MathGL is interpolation and root-finding. There are several functions for linear and cubic spline interpolation (see Interpolation). Also there is a function evaluate which do interpolation of data array for values of each data element of index data. It look as indirect access to the data elements.
-
-
This function have inverse function solve which find array of indexes at which data array is equal to given value (i.e. work as root finding). But solve function have the issue - usually multidimensional data (2d and 3d ones) have an infinite number of indexes which give some value. This is contour lines for 2d data, or isosurface(s) for 3d data. So, solve function will return index only in given direction, assuming that other index(es) are the same as equidistant index(es) of original data. Let me demonstrate this on the following sample.
-
-
zrange 0 1
-new x 20 30 '(x+2)/3*cos(pi*y)'
-new y 20 30 '(x+2)/3*sin(pi*y)'
-new z 20 30 'exp(-6*x^2-2*sin(pi*y)^2)'
-
-subplot 2 1 0:title 'Cartesian space':rotate 30 -40
-axis 'xyzU':box
-xlabel 'x':ylabel 'y'origin 1 1:grid 'xy'
-mesh x y z
-
-# section along 'x' direction
-solve u x 0.5 'x'
-var v u.nx 0 1
-evaluate yy y u v
-evaluate xx x u v
-evaluate zz z u v
-plot xx yy zz 'k2o'
-
-# 1st section along 'y' direction
-solve u1 x -0.5 'y'
-var v1 u1.nx 0 1
-evaluate yy y v1 u1
-evaluate xx x v1 u1
-evaluate zz z v1 u1
-plot xx yy zz 'b2^'
-
-# 2nd section along 'y' direction
-solve u2 x -0.5 'y' u1
-evaluate yy y v1 u2
-evaluate xx x v1 u2
-evaluate zz z v1 u2
-plot xx yy zz 'r2v'
-
-subplot 2 1 1:title 'Accompanied space'
-ranges 0 1 0 1:origin 0 0
-axis:box:xlabel 'i':ylabel 'j':grid2 z 'h'
-
-plot u v 'k2o':line 0.4 0.5 0.8 0.5 'kA'
-plot v1 u1 'b2^':line 0.5 0.15 0.5 0.3 'bA'
-plot v1 u2 'r2v':line 0.5 0.7 0.5 0.85 'rA'
-
Let me now show how to plot the data. Next section will give much more examples for all plotting functions. Here I just show some basics. MathGL generally has 2 types of plotting functions. Simple variant requires a single data array for plotting, other data (coordinates) are considered uniformly distributed in axis range. Second variant requires data arrays for all coordinates. It allows one to plot rather complex multivalent curves and surfaces (in case of parametric dependencies). Usually each function have one textual argument for plot style and accept options (see Command options).
-
-
Note, that the call of drawing function adds something to picture but does not clear the previous plots (as it does in Matlab). Another difference from Matlab is that all setup (like transparency, lightning, axis borders and so on) must be specified before plotting functions.
-
-
Let start for plots for 1D data. Term “1D data” means that data depend on single index (parameter) like curve in parametric form {x(i),y(i),z(i)}, i=1...n. The textual argument allow you specify styles of line and marks (see Line styles). If this parameter is empty '' then solid line with color from palette is used (see Palette and colors).
-
-
Below I shall show the features of 1D plotting on base of plot function. Let us start from sinus plot:
-
Style of line is not specified in plot function. So MathGL uses the solid line with first color of palette (this is blue). Next subplot shows array y1 with 2 rows:
-
As previously I did not specify the style of lines. As a result, MathGL again uses solid line with next colors in palette (there are green and red). Now let us plot a circle on the same subplot. The circle is parametric curve x=cos(\pi t), y=sin(\pi t). I will set the color of the circle (dark yellow, `Y`) and put marks `+` at point position:
-
new x 50 'cos(pi*x)'
-plot x y0 'Y+'
-
Note that solid line is used because I did not specify the type of line. The same picture can be achieved by plot and subdata functions. Let us draw ellipse by orange dash line:
-
plot y1(:,0) y1(:,1) 'q|'
-
-
Drawing in 3D space is mostly the same. Let us draw spiral with default line style. Now its color is 4-th color from palette (this is cyan):
-
subplot 2 2 2:rotate 60 40
-new z 50 'x'
-plot x y0 z:box
-
Functions plot and subdata make 3D curve plot but for single array. Use it to put circle marks on the previous plot:
-
Note that line style is empty `` here. Usage of other 1D plotting functions looks similar:
-
subplot 2 2 3:rotate 60 40
-bars x y0 z 'r':box
-
-
Surfaces surf and other 2D plots (see 2D plotting) are drown the same simpler as 1D one. The difference is that the string parameter specifies not the line style but the color scheme of the plot (see Color scheme). Here I draw attention on 4 most interesting color schemes. There is gray scheme where color is changed from black to white (string `kw`) or from white to black (string `wk`). Another scheme is useful for accentuation of negative (by blue color) and positive (by red color) regions on plot (string `"BbwrR"`). Last one is the popular “jet” scheme (string `"BbcyrR"`).
-
-
Now I shall show the example of a surface drawing. At first let us switch lightning on
-
light on
-
and draw the surface, considering coordinates x,y to be uniformly distributed in axis range
-
Color scheme was not specified. So previous color scheme is used. In this case it is default color scheme (“jet”) for the first plot. Next example is a sphere. The sphere is parametrically specified surface:
-
new x 50 40 '0.8*sin(pi*x)*cos(pi*y/2)'
-new y 50 40 '0.8*cos(pi*x)*cos(pi*y/2)'
-new z 50 40 '0.8*sin(pi*y/2)'
-subplot 2 2 1:rotate 60 40
-surf x y z 'BbwrR':box
-
I set color scheme to "BbwrR" that corresponds to red top and blue bottom of the sphere.
-
-
Surfaces will be plotted for each of slice of the data if nz>1. Next example draws surfaces for data arrays with nz=3:
-
Note, that it may entail a confusion. However, if one will use density plot then the picture will look better:
-
subplot 2 2 3:rotate 60 40
-dens a1:box
-
-
Drawing of other 2D plots is analogous. The only peculiarity is the usage of flag `#`. By default this flag switches on the drawing of a grid on plot (grid or mesh for plots in plain or in volume). However, for isosurfaces (including surfaces of rotation axial) this flag switches the face drawing off and figure becomes wired.
-
In this section I`ve included some small hints and advices for the improving of the quality of plots and for the demonstration of some non-trivial features of MathGL library. In contrast to previous examples I showed mostly the idea but not the whole drawing function.
-
As I noted above, MathGL functions (except the special one, like Clf()) do not erase the previous plotting but just add the new one. It allows one to draw “compound” plots easily. For example, popular Matlab command surfc can be emulated in MathGL by 2 calls:
-
Surf(a);
- Cont(a, "_"); // draw contours at bottom
-
Here a is 2-dimensional data for the plotting, -1 is the value of z-coordinate at which the contour should be plotted (at the bottom in this example). Analogously, one can draw density plot instead of contour lines and so on.
-
-
Another nice plot is contour lines plotted directly on the surface:
-
Light(true); // switch on light for the surface
- Surf(a, "BbcyrR"); // select 'jet' colormap for the surface
- Cont(a, "y"); // and yellow color for contours
-
The possible difficulties arise in black&white case, when the color of the surface can be close to the color of a contour line. In that case I may suggest the following code:
-
Light(true); // switch on light for the surface
- Surf(a, "kw"); // select 'gray' colormap for the surface
- CAxis(-1,0); // first draw for darker surface colors
- Cont(a, "w"); // white contours
- CAxis(0,1); // now draw for brighter surface colors
- Cont(a, "k"); // black contours
- CAxis(-1,1); // return color range to original state
-
The idea is to divide the color range on 2 parts (dark and bright) and to select the contrasting color for contour lines for each of part.
-
-
Similarly, one can plot flow thread over density plot of vector field amplitude (this is another amusing plot from Matlab) and so on. The list of compound graphics can be prolonged but I hope that the general idea is clear.
-
-
Just for illustration I put here following sample code:
-
call 'prepare2v'
-call 'prepare3d'
-new v 10:fill v -0.5 1:copy d sqrt(a^2+b^2)
-subplot 2 2 0:title 'Surf + Cont':rotate 50 60:light on:box
-surf a:cont a 'y'
-
-subplot 2 2 1 '':title 'Flow + Dens':light off:box
-flow a b 'br':dens d
-
-subplot 2 2 2:title 'Mesh + Cont':rotate 50 60:box
-mesh a:cont a '_'
-
-subplot 2 2 3:title 'Surf3 + ContF3':rotate 50 60:light on
-box:contf3 v c 'z' 0:contf3 v c 'x':contf3 v c
-cut 0 -1 -1 1 0 1.1
-contf3 v c 'z' c.nz-1:surf3 c -0.5
-
MathGL library has advanced features for setting and handling the surface transparency. The simplest way to add transparency is the using of command alpha. As a result, all further surfaces (and isosurfaces, density plots and so on) become transparent. However, their look can be additionally improved.
-
-
The value of transparency can be different from surface to surface. To do it just use SetAlphaDef before the drawing of the surface, or use option alpha (see Command options). If its value is close to 0 then the surface becomes more and more transparent. Contrary, if its value is close to 1 then the surface becomes practically non-transparent.
-
-
Also you can change the way how the light goes through overlapped surfaces. The function SetTranspType defines it. By default the usual transparency is used (`0`) - surfaces below is less visible than the upper ones. A “glass-like” transparency (`1`) has a different look - each surface just decreases the background light (the surfaces are commutable in this case).
-
-
A “neon-like” transparency (`2`) has more interesting look. In this case a surface is the light source (like a lamp on the dark background) and just adds some intensity to the color. At this, the library sets automatically the black color for the background and changes the default line color to white.
-
-
As example I shall show several plots for different types of transparency. The code is the same except the values of SetTranspType function:
-
You can easily make 3D plot and draw its x-,y-,z-projections (like in CAD) by using ternary function with arguments: 4 for Cartesian, 5 for Ternary and 6 for Quaternary coordinates. The sample code is:
-
ranges 0 1 0 1 0 1
-new x 50 '0.25*(1+cos(2*pi*x))'
-new y 50 '0.25*(1+sin(2*pi*x))'
-new z 50 'x'
-new a 20 30 '30*x*y*(1-x-y)^2*(x+y<1)'
-new rx 10 'rnd':new ry 10:fill ry '(1-v)*rnd' rx
-light on
-
-title 'Projection sample':ternary 4:rotate 50 60
-box:axis:grid
-plot x y z 'r2':surf a '#'
-xlabel 'X':ylabel 'Y':zlabel 'Z'
-
MathGL can add a fog to the image. Its switching on is rather simple - just use fog function. There is the only feature - fog is applied for whole image. Not to particular subplot. The sample code is:
-
call 'prepare2d'
-title 'Fog sample':rotate 50 60:light on
-fog 1
-box:surf a:cont a 'y'
-
In contrast to the most of other programs, MathGL supports several (up to 10) light sources. Moreover, the color each of them can be different: white (this is usual), yellow, red, cyan, green and so on. The use of several light sources may be interesting for the highlighting of some peculiarities of the plot or just to make an amusing picture. Note, each light source can be switched on/off individually. The sample code is:
-
Additionally, you can use local light sources and set to use diffuse reflection instead of specular one (by default) or both kinds. Note, I use attachlight command to keep light settings relative to subplot.
-
MathGL provide a set of functions for drawing primitives (see Primitives). Primitives are low level object, which used by most of plotting functions. Picture below demonstrate some of commonly used primitives.
-
Generally, you can create arbitrary new kind of plot using primitives. For example, MathGL don`t provide any special functions for drawing molecules. However, you can do it using only one type of primitives drop. The sample code is:
-
Moreover, some of special plots can be more easily produced by primitives rather than by specialized function. For example, Venn diagram can be produced by Error plot:
-
list x -0.3 0 0.3:list y 0.3 -0.3 0.3:list e 0.7 0.7 0.7
-title 'Venn-like diagram':alpha on
-error x y e e '!rgb@#o'
-
You see that you have to specify and fill 3 data arrays. The same picture can be produced by just 3 calls of circle function:
-
title 'Venn-like diagram':alpha on
-circle -0.3 0.3 0.7 'rr@'
-circle 0 -0.3 0.7 'gg@'
-circle 0.3 0.3 0.7 'bb@'
-
Of course, the first variant is more suitable if you need to plot a lot of circles. But for few ones the usage of primitives looks easy.
-
Short-time Fourier Analysis (stfa) is one of informative method for analyzing long rapidly oscillating 1D data arrays. It is used to determine the sinusoidal frequency and phase content of local sections of a signal as it changes over time.
-
-
MathGL can find and draw STFA result. Just to show this feature I give following sample. Initial data arrays is 1D arrays with step-like frequency. Exactly this you can see at bottom on the STFA plot. The sample code is:
-
new a 2000:new b 2000
-fill a 'cos(50*pi*x)*(x<-.5)+cos(100*pi*x)*(x<0)*(x>-.5)+\
-cos(200*pi*x)*(x<.5)*(x>0)+cos(400*pi*x)*(x>.5)'
-
-subplot 1 2 0 '<_':title 'Initial signal'
-plot a:axis:xlabel '\i t'
-
-subplot 1 2 1 '<_':title 'STFA plot'
-stfa a b 64:axis:ylabel '\omega' 0:xlabel '\i t'
-
Sometime ago I worked with mapping and have a question about its visualization. Let me remember you that mapping is some transformation rule for one set of number to another one. The 1d mapping is just an ordinary function - it takes a number and transforms it to another one. The 2d mapping (which I used) is a pair of functions which take 2 numbers and transform them to another 2 ones. Except general plots (like surfc, surfa) there is a special plot - Arnold diagram. It shows the area which is the result of mapping of some initial area (usually square).
-
-
I tried to make such plot in map. It shows the set of points or set of faces, which final position is the result of mapping. At this, the color gives information about their initial position and the height describes Jacobian value of the transformation. Unfortunately, it looks good only for the simplest mapping but for the real multivalent quasi-chaotic mapping it produces a confusion. So, use it if you like :).
-
-
The sample code for mapping visualization is:
-
new a 50 40 'x':new b 50 40 'y':zrange -2 2:text 0 0 '\to'
-subplot 2 1 0:text 0 1.1 '\{x, y\}' '' -2:box
-map a b 'brgk'
-
-subplot 2 1 1:box
-text 0 1.1 '\{\frac{x^3+y^3}{2}, \frac{x-y}{2}\}' '' -2
-fill a '(x^3+y^3)/2':fill b '(x-y)/2':map a b 'brgk'
-
functions subdata and evaluate for indirect access to data elements;
-
functions refill, gspline and datagrid which fill regular (rectangular) data array by interpolated values.
-
-
-
The usage of first category is rather straightforward and don`t need any special comments.
-
-
There is difference in indirect access functions. Function subdata use use step-like interpolation to handle correctly single nan values in the data array. Contrary, function evaluate use local spline interpolation, which give smoother output but spread nan values. So, subdata should be used for specific data elements (for example, for given column), and evaluate should be used for distributed elements (i.e. consider data array as some field). Following sample illustrates this difference:
-
subplot 1 1 0 '':title 'SubData vs Evaluate'
-new in 9 'x^3/1.1':plot in 'ko ':box
-new arg 99 '4*x+4'
-evaluate e in arg off:plot e 'b.'; legend 'Evaluate'
-subdata s in arg:plot s 'r.';legend 'SubData'
-legend 2
-
-
-
-
Example of datagrid usage is done in Making regular data. Here I want to show the peculiarities of refill and gspline functions. Both functions require argument(s) which provide coordinates of the data values, and return rectangular data array which equidistantly distributed in axis range. So, in opposite to evaluate function, refill and gspline can interpolate non-equidistantly distributed data. At this both functions refill and gspline provide continuity of 2nd derivatives along coordinate(s). However, refill is slower but give better (from human point of view) result than global spline gspline due to more advanced algorithm. Following sample illustrates this difference:
-
new x 10 '0.5+rnd':cumsum x 'x':norm x -1 1
-copy y sin(pi*x)/1.5
-subplot 2 2 0 '<_':title 'Refill sample'
-box:axis:plot x y 'o ':fplot 'sin(pi*x)/1.5' 'B:'
-new r 100:refill r x y:plot r 'r'
-
-subplot 2 2 1 '<_':title 'Global spline'
-box:axis:plot x y 'o ':fplot 'sin(pi*x)/1.5' 'B:'
-new r 100:gspline r x y:plot r 'r'
-
-new y 10 '0.5+rnd':cumsum y 'x':norm y -1 1
-copy xx x:extend xx 10
-copy yy y:extend yy 10:transpose yy
-copy z sin(pi*xx*yy)/1.5
-alpha on:light on
-subplot 2 2 2:title '2d regular':rotate 40 60
-box:axis:mesh xx yy z 'k'
-new rr 100 100:refill rr x y z:surf rr
-
-new xx 10 10 '(x+1)/2*cos(y*pi/2-1)'
-new yy 10 10 '(x+1)/2*sin(y*pi/2-1)'
-copy z sin(pi*xx*yy)/1.5
-subplot 2 2 3:title '2d non-regular':rotate 40 60
-box:axis:plot xx yy z 'ko '
-new rr 100 100:refill rr xx yy z:surf rr
-
Sometimes, one have only unregular data, like as data on triangular grids, or experimental results and so on. Such kind of data cannot be used as simple as regular data (like matrices). Only few functions, like dots, can handle unregular data as is.
-
-
However, one can use built in triangulation functions for interpolating unregular data points to a regular data grids. There are 2 ways. First way, one can use triangulation function to obtain list of vertexes for triangles. Later this list can be used in functions like triplot or tricont. Second way consist in usage of datagrid function, which fill regular data grid by interpolated values, assuming that coordinates of the data grid is equidistantly distributed in axis range. Note, you can use options (see Command options) to change default axis range as well as in other plotting functions.
-
new x 100 '2*rnd-1':new y 100 '2*rnd-1':copy z x^2-y^2
-# first way - plot triangular surface for points
-triangulate d x y
-title 'Triangulation'
-rotate 50 60:box:light on
-triplot d x y z:triplot d x y z '#k'
-# second way - make regular data and plot it
-new g 30 30:datagrid g x y z:mesh g 'm'
-
Using the hist function(s) for making regular distributions is one of useful fast methods to process and plot irregular data. Hist can be used to find some momentum of set of points by specifying weight function. It is possible to create not only 1D distributions but also 2D and 3D ones. Below I place the simplest sample code which demonstrate hist usage:
-
new x 10000 '2*rnd-1':new y 10000 '2*rnd-1':copy z exp(-6*(x^2+y^2))
-hist xx x z:norm xx 0 1:hist yy y z:norm yy 0 1
-multiplot 3 3 3 2 2 '':ranges -1 1 -1 1 0 1:box:dots x y z 'wyrRk'
-multiplot 3 3 0 2 1 '':ranges -1 1 0 1:box:bars xx
-multiplot 3 3 5 1 2 '':ranges 0 1 -1 1:box:barh yy
-subplot 3 3 2:text 0.5 0.5 'Hist and\n{}MultiPlot\n{}sample' 'a' -3
-
Nonlinear fitting is rather simple. All that you need is the data to fit, the approximation formula and the list of coefficients to fit (better with its initial guess values). Let me demonstrate it on the following simple example. First, let us use sin function with some random noise:
-
new dat 100 '0.4*rnd+0.1+sin(2*pi*x)'
-new in 100 '0.3+sin(2*pi*x)'
-
and plot it to see that data we will fit
-
title 'Fitting sample':yrange -2 2:box:axis:plot dat 'k. '
-
-
The next step is the fitting itself. For that let me specify an initial values ini for coefficients `abc` and do the fitting for approximation formula `a+b*sin(c*x)`
-
list ini 1 1 3:fit res dat 'a+b*sin(c*x)' 'abc' ini
-
Now display it
-
plot res 'r':plot in 'b'
-text -0.9 -1.3 'fitted:' 'r:L'
-putsfit 0 -1.8 'y = ' 'r'
-text 0 2.2 'initial: y = 0.3+sin(2\pi x)' 'b'
-
-
NOTE! the fitting results may have strong dependence on initial values for coefficients due to algorithm features. The problem is that in general case there are several local "optimums" for coefficients and the program returns only first found one! There are no guaranties that it will be the best. Try for example to set ini[3] = {0, 0, 0} in the code above.
-
-
The full sample code for nonlinear fitting is:
-
new dat 100 '0.4*rnd+0.1+sin(2*pi*x)'
-new in 100 '0.3+sin(2*pi*x)'
-list ini 1 1 3:fit res dat 'a+b*sin(c*x)' 'abc' ini
-title 'Fitting sample':yrange -2 2:box:axis:plot dat 'k. '
-plot res 'r':plot in 'b'
-text -0.9 -1.3 'fitted:' 'r:L'
-putsfit 0 -1.8 'y = ' 'r'
-text 0 2.2 'initial: y = 0.3+sin(2\pi x)' 'b'
-
Solving of Partial Differential Equations (PDE, including beam tracing) and ray tracing (or finding particle trajectory) are more or less common task. So, MathGL have several functions for that. There are ray for ray tracing, pde for PDE solving, qo2d for beam tracing in 2D case (see Global functions). Note, that these functions take “Hamiltonian” or equations as string values. And I don`t plan now to allow one to use user-defined functions. There are 2 reasons: the complexity of corresponding interface; and the basic nature of used methods which are good for samples but may not good for serious scientific calculations.
-
-
The ray tracing can be done by ray function. Really ray tracing equation is Hamiltonian equation for 3D space. So, the function can be also used for finding a particle trajectory (i.e. solve Hamiltonian ODE) for 1D, 2D or 3D cases. The function have a set of arguments. First of all, it is Hamiltonian which defined the media (or the equation) you are planning to use. The Hamiltonian is defined by string which may depend on coordinates `x`, `y`, `z`, time `t` (for particle dynamics) and momentums `p`=p_x, `q`=p_y, `v`=p_z. Next, you have to define the initial conditions for coordinates and momentums at `t`=0 and set the integrations step (default is 0.1) and its duration (default is 10). The Runge-Kutta method of 4-th order is used for integration.
-
This example calculate the reflection from linear layer (media with Hamiltonian `p^2+q^2-x-1`=p_x^2+p_y^2-x-1). This is parabolic curve. The resulting array have 7 columns which contain data for {x,y,z,p,q,v,t}.
-
-
The solution of PDE is a bit more complicated. As previous you have to specify the equation as pseudo-differential operator \hat H(x, \nabla) which is called sometime as “Hamiltonian” (for example, in beam tracing). As previously, it is defined by string which may depend on coordinates `x`, `y`, `z` (but not time!), momentums `p`=(d/dx)/i k_0, `q`=(d/dy)/i k_0 and field amplitude `u`=|u|. The evolutionary coordinate is `z` in all cases. So that, the equation look like du/dz = ik_0 H(x,y,\hat p, \hat q, |u|)[u]. Dependence on field amplitude `u`=|u| allows one to solve nonlinear problems too. For example, for nonlinear Shrodinger equation you may set ham="p^2 + q^2 - u^2". Also you may specify imaginary part for wave absorption, like ham = "p^2 + i*x*(x>0)" or ham = "p^2 + i1*x*(x>0)".
-
-
Next step is specifying the initial conditions at `z` equal to minimal z-axis value. The function need 2 arrays for real and for imaginary part. Note, that coordinates x,y,z are supposed to be in specified axis range. So, the data arrays should have corresponding scales. Finally, you may set the integration step and parameter k0=k_0. Also keep in mind, that internally the 2 times large box is used (for suppressing numerical reflection from boundaries) and the equation should well defined even in this extended range.
-
-
Final comment is concerning the possible form of pseudo-differential operator H. At this moment, simplified form of operator H is supported - all “mixed” terms (like `x*p`->x*d/dx) are excluded. For example, in 2D case this operator is effectively H = f(p,z) + g(x,z,u). However commutable combinations (like `x*q`->x*d/dy) are allowed for 3D case.
-
-
So, for example let solve the equation for beam deflected from linear layer and absorbed later. The operator will have the form `"p^2+q^2-x-1+i*0.5*(z+x)*(z>-x)"` that correspond to equation 1/ik_0 * du/dz + d^2 u/dx^2 + d^2 u/dy^2 + x * u + i (x+z)/2 * u = 0. This is typical equation for Electron Cyclotron (EC) absorption in magnetized plasmas. For initial conditions let me select the beam with plane phase front exp(-48*(x+0.7)^2). The corresponding code looks like this:
-
new re 128 'exp(-48*(x+0.7)^2)':new im 128
-pde a 'p^2+q^2-x-1+i*0.5*(z+x)*(z>-x)' re im 0.01 30
-transpose a
-subplot 1 1 0 '<_':title 'PDE solver'
-axis:xlabel '\i x':ylabel '\i z'
-crange 0 1:dens a 'wyrRk'
-fplot '-x' 'k|'
-text 0 0.95 'Equation: ik_0\partial_zu + \Delta u + x\cdot u +\
- i \frac{x+z}{2}\cdot u = 0\n{}absorption: (x+z)/2 for x+z>0'
-
-
-
-
The next example is example of beam tracing. Beam tracing equation is special kind of PDE equation written in coordinates accompanied to a ray. Generally this is the same parameters and limitation as for PDE solving but the coordinates are defined by the ray and by parameter of grid width w in direction transverse the ray. So, you don`t need to specify the range of coordinates. BUT there is limitation. The accompanied coordinates are well defined only for smooth enough rays, i.e. then the ray curvature K (which is defined as 1/K^2 = (|r''|^2 |r'|^2 - (r'', r'')^2)/|r'|^6) is much large then the grid width: K>>w. So, you may receive incorrect results if this condition will be broken.
-
-
You may use following code for obtaining the same solution as in previous example:
-
define $1 'p^2+q^2-x-1+i*0.5*(y+x)*(y>-x)'
-subplot 1 1 0 '<_':title 'Beam and ray tracing'
-ray r $1 -0.7 -1 0 0 0.5 0 0.02 2:plot r(0) r(1) 'k'
-axis:xlabel '\i x':ylabel '\i z'
-new re 128 'exp(-48*x^2)':new im 128
-new xx 1:new yy 1
-qo2d a $1 re im r 1 30 xx yy
-crange 0 1:dens xx yy a 'wyrRk':fplot '-x' 'k|'
-text 0 0.85 'absorption: (x+y)/2 for x+y>0'
-text 0.7 -0.05 'central ray'
-
-
-
-
Note, the pde is fast enough and suitable for many cases routine. However, there is situations then media have both together: strong spatial dispersion and spatial inhomogeneity. In this, case the pde will produce incorrect result and you need to use advanced PDE solver apde. For example, a wave beam, propagated in plasma, described by Hamiltonian exp(-x^2-p^2), will have different solution for using of simplification and advanced PDE solver:
-
Here I want say a few words of plotting phase plains. Phase plain is name for system of coordinates x, x', i.e. a variable and its time derivative. Plot in phase plain is very useful for qualitative analysis of an ODE, because such plot is rude (it topologically the same for a range of ODE parameters). Most often the phase plain {x, x'} is used (due to its simplicity), that allows to analyze up to the 2nd order ODE (i.e. x''+f(x,x')=0).
-
-
The simplest way to draw phase plain in MathGL is using flow function(s), which automatically select several points and draw flow threads. If the ODE have an integral of motion (like Hamiltonian H(x,x')=const for dissipation-free case) then you can use cont function for plotting isolines (contours). In fact. isolines are the same as flow threads, but without arrows on it. Finally, you can directly solve ODE using ode function and plot its numerical solution.
-
-
Let demonstrate this for ODE equation x''-x+3*x^2=0. This is nonlinear oscillator with square nonlinearity. It has integral H=y^2+2*x^3-x^2=Const. Also it have 2 typical stationary points: saddle at {x=0, y=0} and center at {x=1/3, y=0}. Motion at vicinity of center is just simple oscillations, and is stable to small variation of parameters. In opposite, motion around saddle point is non-stable to small variation of parameters, and is very slow. So, calculation around saddle points are more difficult, but more important. Saddle points are responsible for solitons, stochasticity and so on.
-
-
So, let draw this phase plain by 3 different methods. First, draw isolines for H=y^2+2*x^3-x^2=Const - this is simplest for ODE without dissipation. Next, draw flow threads - this is straightforward way, but the automatic choice of starting points is not always optimal. Finally, use ode to check the above plots. At this we need to run ode in both direction of time (in future and in the past) to draw whole plain. Alternatively, one can put starting points far from (or at the bounding box as done in flow) the plot, but this is a more complicated. The sample code is:
-
There is common task in optics to determine properties of wave pulses or wave beams. MathGL provide special function pulse which return the pulse properties (maximal value, center of mass, width and so on). Its usage is rather simple. Here I just illustrate it on the example of Gaussian pulse, where all parameters are obvious.
-
subplot 1 1 0 '<_':title 'Pulse sample'
-# first prepare pulse itself
-new a 100 'exp(-6*x^2)'
-
-# get pulse parameters
-pulse b a 'x'
-
-# positions and widths are normalized on the number of points. So, set proper axis scale.
-ranges 0 a.nx-1 0 1
-axis:plot a # draw pulse and axis
-
-# now visualize found pulse properties
-define m a.max # maximal amplitude
-# approximate position of maximum
-line b(1) 0 b(1) m 'r='
-# width at half-maximum (so called FWHM)
-line b(1)-b(3)/2 0 b(1)-b(3)/2 m 'm|'
-line b(1)+b(3)/2 0 b(1)+b(3)/2 m 'm|'
-line 0 0.5*m a.nx-1 0.5*m 'h'
-# parabolic approximation near maximum
-new x 100 'x'
-plot b(0)*(1-((x-b(1))/b(2))^2) 'g'
-
Command options allow the easy setup of the selected plot by changing global settings only for this plot. Often, options are used for specifying the range of automatic variables (coordinates). However, options allows easily change plot transparency, numbers of line or faces to be drawn, or add legend entries. The sample function for options usage is:
-
new a 31 41 '-pi*x*exp(-(y+1)^2-4*x^2)'
-alpha on:light on
-subplot 2 2 0:title 'Options for coordinates':rotate 40 60:box
-surf a 'r';yrange 0 1
-surf a 'b';yrange 0 -1
-
-subplot 2 2 1:title 'Option "meshnum"':rotate 40 60:box
-mesh a 'r'; yrange 0 1
-mesh a 'b';yrange 0 -1; meshnum 5
-
-subplot 2 2 2:title 'Option "alpha"':rotate 40 60:box
-surf a 'r';yrange 0 1; alpha 0.7
-surf a 'b';yrange 0 -1; alpha 0.3
-
-subplot 2 2 3 '<_':title 'Option "legend"'
-fplot 'x^3' 'r'; legend 'y = x^3'
-fplot 'cos(pi*x)' 'b'; legend 'y = cos \pi x'
-box:axis:legend 2
-
As I have noted before, the change of settings will influence only for the further plotting commands. This allows one to create “template” function which will contain settings and primitive drawing for often used plots. Correspondingly one may call this template-function for drawing simplification.
-
-
For example, let one has a set of points (experimental or numerical) and wants to compare it with theoretical law (for example, with exponent law \exp(-x/2), x \in [0, 20]). The template-function for this task is:
-
At this, one will only write a few lines for data drawing:
-
template(gr); // apply settings and default drawing from template
- mglData dat("fname.dat"); // load the data
- // and draw it (suppose that data file have 2 columns)
- gr->Plot(dat.SubData(0),dat.SubData(1),"bx ");
-
A template-function can also contain settings for font, transparency, lightning, color scheme and so on.
-
-
I understand that this is obvious thing for any professional programmer, but I several times receive suggestion about “templates” ... So, I decide to point out it here.
-
One can easily create stereo image in MathGL. Stereo image can be produced by making two subplots with slightly different rotation angles. The corresponding code looks like this:
-
call 'prepare2d'
-light on
-subplot 2 1 0:rotate 50 60+1:box:surf a
-subplot 2 1 1:rotate 50 60-1:box:surf a
-
By default MathGL save all primitives in memory, rearrange it and only later draw them on bitmaps. Usually, this speed up drawing, but may require a lot of memory for plots which contain a lot of faces (like cloud, dew). You can use quality function for setting to use direct drawing on bitmap and bypassing keeping any primitives in memory. This function also allow you to decrease the quality of the resulting image but increase the speed of the drawing.
-
-
The code for lower memory usage looks like this:
-
quality 6 # firstly, set to draw directly on bitmap
-for $1 0 1000
- sphere 2*rnd-1 2*rnd-1 0.05
-next
-
MathGL have possibilities to write textual information into file with variable values by help of save command. This is rather useful for generating an ini-files or preparing human-readable textual files. For example, lets create some textual file
-
subplot 1 1 0 '<_':title 'Save and scanfile sample'
-list a 1 -1 0
-save 'This is test: 0 -> ',a(0),' q' 'test.txt' 'w'
-save 'This is test: 1 -> ',a(1),' q' 'test.txt'
-save 'This is test: 2 -> ',a(2),' q' 'test.txt'
-
It contents look like
-
This is test: 0 -> 1 q
-This is test: 1 -> -1 q
-This is test: 2 -> 0 q
-
Note, that I use option `w` at first call of save to overwrite the contents of the file.
-
-
Let assume now that you want to read this values (i.e. [[0,1],[1,-1],[2,0]]) from the file. You can use scanfile for that. The desired values was written using template `This is test: %g -> %g q`. So, just use
-
scanfile a 'test.txt' 'This is test: %g -> %g'
-
and plot it to for assurance
-
ranges a(0) a(1):axis:plot a(0) a(1) 'o'
-
-
Note, I keep only the leading part of template (i.e. `This is test: %g -> %g` instead of `This is test: %g -> %g q`), because there is no important for us information after the second number in the line.
-
Sometimes output plots contain surfaces with a lot of points, and some vector primitives (like axis, text, curves, etc.). Using vector output formats (like EPS or SVG) will produce huge files with possible loss of smoothed lighting. Contrary, the bitmap output may cause the roughness of text and curves. Hopefully, MathGL have a possibility to combine bitmap output for surfaces and vector one for other primitives in the same EPS file, by using rasterize command.
-
-
The idea is to prepare part of picture with surfaces or other "heavy" plots and produce the background image from them by help of rasterize command. Next, we draw everything to be saved in vector form (text, curves, axis and etc.). Note, that you need to clear primitives (use clf command) after rasterize if you want to disable duplication of surfaces in output files (like EPS). Note, that some of output formats (like 3D ones, and TeX) don`t support the background bitmap, and use clf for them will cause the loss of part of picture.
-
-
The sample code is:
-
# first draw everything to be in bitmap output
-fsurf 'x^2+y^2' '#';value 10
-
-rasterize # set above plots as bitmap background
-clf # clear primitives, to exclude them from file
-
-# now draw everything to be in vector output
-axis:box
-
-# and save file
-write 'fname.eps'
-
Check that points of the plot are located inside the bounding box and resize the bounding box using ranges function. Check that the data have correct dimensions for selected type of plot. Sometimes the light reflection from flat surfaces (like, dens) can look as if the plot were absent.
-
-
-
I can not find some special kind of plot.
-
Most “new” types of plots can be created by using the existing drawing functions. For example, the surface of curve rotation can be created by a special function torus, or as a parametrically specified surface by surf. See also, Hints. If you can not find a specific type of plot, please e-mail me and this plot will appear in the next version of MathGL library.
-
-
-
How can I print in Russian/Spanish/Arabic/Japanese, and so on?
-
The standard way is to use Unicode encoding for the text output. But the MathGL library also has interface for 8-bit (char *) strings with internal conversion to Unicode. This conversion depends on the current locale OS.
-
-
-
How can I exclude a point or a region of plot from the drawing?
-
There are 3 general ways. First, the point with nan value as one of the coordinates (including color/alpha range) will never be plotted. Second, special functions define the condition when the points should be omitted (see Cutting). Last, you may change the transparency of a part of the plot by the help of functions surfa, surf3a (see Dual plotting). In last case the transparency is switched on smoothly.
-
-
-
How many people write this library?
-
Most of the library was written by one person. This is a result of nearly a year of work (mostly in the evening and on holidays): I spent half a year to write the kernel and half a year to a year on extending, improving the library and writing documentation. This process continues now :). The build system (cmake files) was written mostly by D.Kulagin, and the export to PRC/PDF was written mostly by M.Vidassov.
-
-
-
How can I display a bitmap on the figure?
-
You can import data by command import and display it by dens function. For example, for black-and-white bitmap you can use the code: import bmp 'fname.png' 'wk':dens bmp 'wk'.
-
-
-
-
How can I create 3D in PDF?
-
Just use command write fname.pdf, which create PDF file if enable-pdf=ON at MathGL configure.
-
-
-
How can I create TeX figure?
-
Just use command write fname.tex, which create LaTeX files with figure itself `fname.tex`, with MathGL colors `mglcolors.tex` and main file `mglmain.tex`. Last one can be used for viewing image by command like pdflatex mglmain.tex.
-
-
-
-
How I can change the font family?
-
First, you should download new font files from here or from here. Next, you should load the font files into by the following command: loadfont 'fontname'. Here fontname is the base font name like `STIX`. Use loadfont '' to start using the default font.
-
-
-
How can I draw tick out of a bounding box?
-
Just set a negative value in ticklen. For example, use ticklen -0.1.
-
-
-
How can I prevent text rotation?
-
Just use rotatetext off. Also you can use axis style `U` for disable only tick labels rotation.
-
-
-
How can I draw equal axis range even for rectangular image?
-
Just use aspect nan nan for each subplot, or at the beginning of the drawing.
-
Yes. Sometimes you may have huge surface and a small set of curves and/or text on the plot. You can use function rasterize just after making surface plot. This will put all plot to bitmap background. At this later plotting will be in vector format. For example, you can do something like following:
-
surf x y z
-rasterize # make surface as bitmap
-axis
-write 'fname.eps'
-
Function axial draw surfaces of rotation for contour lines. You can draw wire surfaces (`#` style) or ones rotated in other directions (`x`, `z` styles).
-
Function bars draw vertical bars. It have a lot of options: bar-above-bar (`a` style), fall like (`f` style), 2 colors for positive and negative values, wired bars (`#` style), 3D variant.
-
Function candle draw candlestick chart. This is a combination of a line-chart and a bar-chart, in that each bar represents the range of price movement over a given time interval.
-
-
MGL code:
-
new y 30 'sin(pi*x/2)^2'
-subplot 1 1 0 '':title 'Candle plot (default)'
-yrange 0 1:box
-candle y y/2 (y+1)/2
-
Function chart draw colored boxes with width proportional to data values. Use `` for empty box. It produce well known pie chart if drawn in polar coordinates.
-
Function cloud draw cloud-like object which is less transparent for higher data values. Similar plot can be created using many (about 10...20 - surf3a a a;value 10) isosurfaces surf3a.
-
call 'prepare2v'
-call 'prepare3d'
-new v 10:fill v -0.5 1:copy d sqrt(a^2+b^2)
-subplot 2 2 0:title 'Surf + Cont':rotate 50 60:light on:box:surf a:cont a 'y'
-subplot 2 2 1 '':title 'Flow + Dens':light off:box:flow a b 'br':dens d
-subplot 2 2 2:title 'Mesh + Cont':rotate 50 60:box:mesh a:cont a '_'
-subplot 2 2 3:title 'Surf3 + ContF3':rotate 50 60:light on
-box:contf3 v c 'z' 0:contf3 v c 'x':contf3 v c
-cut 0 -1 -1 1 0 1.1
-contf3 v c 'z' c.nz-1:surf3 c -0.5
-
Function cont draw contour lines for surface. You can select automatic (default) or manual levels for contours, print contour labels, draw it on the surface (default) or at plane (as Dens).
-
-
MGL code:
-
call 'prepare2d'
-list v -0.5 -0.15 0 0.15 0.5
-subplot 2 2 0:title 'Cont plot (default)':rotate 50 60:box:cont a
-subplot 2 2 1:title 'manual levels':rotate 50 60:box:cont v a
-subplot 2 2 2:title '"\_" and "." styles':rotate 50 60:box:cont a '_':cont a '_.2k'
-subplot 2 2 3 '':title '"t" style':box:cont a 't'
-
Functions contz, conty, contx draw contour lines on plane perpendicular to corresponding axis. One of possible application is drawing projections of 3D field.
-
-
MGL code:
-
call 'prepare3d'
-title 'Cont[XYZ] sample':rotate 50 60:box
-contx {sum c 'x'} '' -1:conty {sum c 'y'} '' 1:contz {sum c 'z'} '' -1
-
Functions contfz, contfy, contfx, draw filled contours on plane perpendicular to corresponding axis. One of possible application is drawing projections of 3D field.
-
-
MGL code:
-
call 'prepare3d'
-title 'ContF[XYZ] sample':rotate 50 60:box
-contfx {sum c 'x'} '' -1:contfy {sum c 'y'} '' 1:contfz {sum c 'z'} '' -1
-
new a 100 'exp(-10*x^2)'
-new b 100 'exp(-10*(x+0.5)^2)'
-yrange 0 1
-subplot 1 2 0 '_':title 'Input fields'
-plot a:plot b:box:axis
-correl r a b 'x'
-norm r 0 1:swap r 'x' # make it human readable
-subplot 1 2 1 '_':title 'Correlation of a and b'
-plot r 'r':axis:box
-line 0.5 0 0.5 1 'B|'
-
new a 40 50 60 'exp(-x^2-4*y^2-16*z^2)'
-light on:alpha on
-copy b a:diff b 'x':subplot 5 3 0:call 'splot'
-copy b a:diff2 b 'x':subplot 5 3 1:call 'splot'
-copy b a:cumsum b 'x':subplot 5 3 2:call 'splot'
-copy b a:integrate b 'x':subplot 5 3 3:call 'splot'
-mirror b 'x':subplot 5 3 4:call 'splot'
-copy b a:diff b 'y':subplot 5 3 5:call 'splot'
-copy b a:diff2 b 'y':subplot 5 3 6:call 'splot'
-copy b a:cumsum b 'y':subplot 5 3 7:call 'splot'
-copy b a:integrate b 'y':subplot 5 3 8:call 'splot'
-mirror b 'y':subplot 5 3 9:call 'splot'
-copy b a:diff b 'z':subplot 5 3 10:call 'splot'
-copy b a:diff2 b 'z':subplot 5 3 11:call 'splot'
-copy b a:cumsum b 'z':subplot 5 3 12:call 'splot'
-copy b a:integrate b 'z':subplot 5 3 13:call 'splot'
-mirror b 'z':subplot 5 3 14:call 'splot'
-stop
-func splot 0
-title 'max=',b.max:norm b -1 1 on:rotate 70 60:box:surf3 b
-return
-
new a 40 50 60 'exp(-x^2-4*y^2-16*z^2)'
-light on:alpha on
-copy b a:sinfft b 'x':subplot 5 3 0:call 'splot'
-copy b a:cosfft b 'x':subplot 5 3 1:call 'splot'
-copy b a:hankel b 'x':subplot 5 3 2:call 'splot'
-copy b a:swap b 'x':subplot 5 3 3:call 'splot'
-copy b a:smooth b 'x':subplot 5 3 4:call 'splot'
-copy b a:sinfft b 'y':subplot 5 3 5:call 'splot'
-copy b a:cosfft b 'y':subplot 5 3 6:call 'splot'
-copy b a:hankel b 'y':subplot 5 3 7:call 'splot'
-copy b a:swap b 'y':subplot 5 3 8:call 'splot'
-copy b a:smooth b 'y':subplot 5 3 9:call 'splot'
-copy b a:sinfft b 'z':subplot 5 3 10:call 'splot'
-copy b a:cosfft b 'z':subplot 5 3 11:call 'splot'
-copy b a:hankel b 'z':subplot 5 3 12:call 'splot'
-copy b a:swap b 'z':subplot 5 3 13:call 'splot'
-copy b a:smooth b 'z':subplot 5 3 14:call 'splot'
-stop
-func splot 0
-title 'max=',b.max:norm b -1 1 on:rotate 70 60:box
-surf3 b 0.5:surf3 b -0.5
-return
-
Functions densz, densy, densx draw density plot on plane perpendicular to corresponding axis. One of possible application is drawing projections of 3D field.
-
-
MGL code:
-
call 'prepare3d'
-title 'Dens[XYZ] sample':rotate 50 60:box
-densx {sum c 'x'} '' -1:densy {sum c 'y'} '' 1:densz {sum c 'z'} '' -1
-
define n 32 #number of points
-define m 20 # number of iterations
-define dt 0.01 # time step
-new res n m+1
-ranges -1 1 0 m*dt 0 1
-
-#tridmat periodic variant
-new !a n 'i',dt*(n/2)^2/2
-copy !b !(1-2*a)
-
-new !u n 'exp(-6*x^2)'
-put res u all 0
-for $i 0 m
-tridmat u a b a u 'xdc'
-put res u all $i+1
-next
-subplot 2 2 0 '<_':title 'Tridmat, periodic b.c.'
-axis:box:dens res
-
-#fourier variant
-new k n:fillsample k 'xk'
-copy !e !exp(-i1*dt*k^2)
-
-new !u n 'exp(-6*x^2)'
-put res u all 0
-for $i 0 m
-fourier u 'x'
-multo u e
-fourier u 'ix'
-put res u all $i+1
-next
-subplot 2 2 1 '<_':title 'Fourier method'
-axis:box:dens res
-
-#tridmat zero variant
-new !u n 'exp(-6*x^2)'
-put res u all 0
-for $i 0 m
-tridmat u a b a u 'xd'
-put res u all $i+1
-next
-subplot 2 2 2 '<_':title 'Tridmat, zero b.c.'
-axis:box:dens res
-
-#diffract exp variant
-new !u n 'exp(-6*x^2)'
-define q dt*(n/2)^2/8 # need q<0.4 !!!
-put res u all 0
-for $i 0 m
-for $j 1 8 # due to smaller dt
-diffract u 'xe' q
-next
-put res u all $i+1
-next
-subplot 2 2 3 '<_':title 'Diffract, exp b.c.'
-axis:box:dens res
-
Function dots is another way to draw irregular points. Dots use color scheme for coloring (see Color scheme).
-
-
MGL code:
-
new t 2000 'pi*(rnd-0.5)':new f 2000 '2*pi*rnd'
-copy x 0.9*cos(t)*cos(f):copy y 0.9*cos(t)*sin(f):copy z 0.6*sin(t):copy c cos(2*t)
-subplot 2 2 0:title 'Dots sample':rotate 50 60
-box:dots x y z
-alpha on
-subplot 2 2 1:title 'add transparency':rotate 50 60
-box:dots x y z c
-subplot 2 2 2:title 'add colorings':rotate 50 60
-box:dots x y z x c
-subplot 2 2 3:title 'Only coloring':rotate 50 60
-box:tens x y z x ' .'
-
import dat 'Equirectangular-projection.jpg' 'BbGYw' -1 1
-subplot 1 1 0 '<>':title 'Earth in 3D':rotate 40 60
-copy phi dat 'pi*x':copy tet dat 'pi*y/2'
-copy x cos(tet)*cos(phi)
-copy y cos(tet)*sin(phi)
-copy z sin(tet)
-
-light on
-surfc x y z dat 'BbGYw'
-contp [-0.51,-0.51] x y z dat 'y'
-
Function error draw error boxes around the points. You can draw default boxes or semi-transparent symbol (like marker, see Line styles). Also you can set individual color for each box. See also error2 sample.
-
new a 100 100 'x^2*y':new b 100 100
-export a 'test_data.png' 'BbcyrR' -1 1
-import b 'test_data.png' 'BbcyrR' -1 1
-subplot 2 1 0 '':title 'initial':box:dens a
-subplot 2 1 1 '':title 'imported':box:dens b
-
Function fall draw waterfall surface. You can use meshnum for changing number of lines to be drawn. Also you can use `x` style for drawing lines in other direction.
-
-
MGL code:
-
call 'prepare2d'
-title 'Fall plot':rotate 50 60:box:fall a
-
new dat 100 '0.4*rnd+0.1+sin(2*pi*x)'
-new in 100 '0.3+sin(2*pi*x)'
-list ini 1 1 3:fit res dat 'a+b*sin(c*x)' 'abc' ini
-title 'Fitting sample':yrange -2 2:box:axis:plot dat 'k. '
-plot res 'r':plot in 'b'
-text -0.9 -1.3 'fitted:' 'r:L'
-putsfit 0 -1.8 'y = ' 'r':text 0 2.2 'initial: y = 0.3+sin(2\pi x)' 'b'
-
Function flame2d generate points for flame fractals in 2d case.
-
-
MGL code:
-
list A [0.33,0,0,0.33,0,0,0.2] [0.33,0,0,0.33,0.67,0,0.2] [0.33,0,0,0.33,0.33,0.33,0.2]\
- [0.33,0,0,0.33,0,0.67,0.2] [0.33,0,0,0.33,0.67,0.67,0.2]
-new B 2 3 A.ny '0.3'
-put B 3 0 0 -1
-put B 3 0 1 -1
-put B 3 0 2 -1
-flame2d fx fy A B 1000000
-subplot 1 1 0 '<_':title 'Flame2d sample'
-ranges fx fy:box:axis
-plot fx fy 'r#o ';size 0.05
-
Function flow is another standard way to visualize vector fields - it draw lines (threads) which is tangent to local vector field direction. MathGL draw threads from edges of bounding box and from central slices. Sometimes it is not most appropriate variant - you may want to use flowp to specify manual position of threads. The color scheme is used for coloring (see Color scheme). At this warm color corresponds to normal flow (like attractor), cold one corresponds to inverse flow (like source).
-
-
MGL code:
-
call 'prepare2v'
-call 'prepare3v'
-subplot 2 2 0 '':title 'Flow plot (default)':box:flow a b
-subplot 2 2 1 '':title '"v" style':box:flow a b 'v'
-subplot 2 2 2 '':title '"#" and "." styles':box:flow a b '#':flow a b '.2k'
-subplot 2 2 3:title '3d variant':rotate 50 60:box:flow ex ey ez
-
Function flow3 draw flow threads, which start from given plane.
-
-
MGL code:
-
call 'prepare3v'
-subplot 2 2 0:title 'Flow3 plot (default)':rotate 50 60:box
-flow3 ex ey ez
-subplot 2 2 1:title '"v" style, from boundary':rotate 50 60:box
-flow3 ex ey ez 'v' 0
-subplot 2 2 2:title '"t" style':rotate 50 60:box
-flow3 ex ey ez 't' 0
-subplot 2 2 3:title 'from \i z planes':rotate 50 60:box
-flow3 ex ey ez 'z' 0
-flow3 ex ey ez 'z' 9
-
subplot 1 1 0 '':title 'SubData vs Evaluate'
-new in 9 'x^3/1.1':plot in 'ko ':box
-new arg 99 '4*x+4'
-evaluate e in arg off:plot e 'b.'; legend 'Evaluate'
-subdata s in arg:plot s 'r.';legend 'SubData'
-legend 2
-
Function ohlc draw Open-High-Low-Close diagram. This diagram show vertical line for between maximal(high) and minimal(low) values, as well as horizontal lines before/after vertical line for initial(open)/final(close) values of some process.
-
-
MGL code:
-
new o 10 '0.5*sin(pi*x)'
-new c 10 '0.5*sin(pi*(x+2/9))'
-new l 10 '0.3*rnd-0.8'
-new h 10 '0.3*rnd+0.5'
-subplot 1 1 0 '':title 'OHLC plot':box:ohlc o h l c
-
new x 100 'sin(pi*x)'
-new y 100 'cos(pi*x)'
-new z 100 'sin(2*pi*x)'
-new c 100 'cos(2*pi*x)'
-
-subplot 4 3 0:rotate 40 60:box:plot x y z
-subplot 4 3 1:rotate 40 60:box:area x y z
-subplot 4 3 2:rotate 40 60:box:tens x y z c
-subplot 4 3 3:rotate 40 60:box:bars x y z
-subplot 4 3 4:rotate 40 60:box:stem x y z
-subplot 4 3 5:rotate 40 60:box:textmark x y z c*2 '\alpha'
-subplot 4 3 6:rotate 40 60:box:tube x y z c/10
-subplot 4 3 7:rotate 40 60:box:mark x y z c 's'
-subplot 4 3 8:box:error x y z/10 c/10
-subplot 4 3 9:rotate 40 60:box:step x y z
-subplot 4 3 10:rotate 40 60:box:torus x z 'z';light on
-subplot 4 3 11:rotate 40 60:box:label x y z '%z'
-
new x 100 100 'sin(pi*(x+y)/2)*cos(pi*y/2)'
-new y 100 100 'cos(pi*(x+y)/2)*cos(pi*y/2)'
-new z 100 100 'sin(pi*y/2)'
-new c 100 100 'cos(pi*x)'
-
-subplot 4 4 0:rotate 40 60:box:surf x y z
-subplot 4 4 1:rotate 40 60:box:surfc x y z c
-subplot 4 4 2:rotate 40 60:box:surfa x y z c;alpha 1
-subplot 4 4 3:rotate 40 60:box:mesh x y z;meshnum 10
-subplot 4 4 4:rotate 40 60:box:tile x y z;meshnum 10
-subplot 4 4 5:rotate 40 60:box:tiles x y z c;meshnum 10
-subplot 4 4 6:rotate 40 60:box:axial x y z;alpha 0.5;light on
-subplot 4 4 7:rotate 40 60:box:cont x y z
-subplot 4 4 8:rotate 40 60:box:contf x y z;light on:contv x y z;light on
-subplot 4 4 9:rotate 40 60:box:belt x y z 'x';meshnum 10;light on
-subplot 4 4 10:rotate 40 60:box:dens x y z;alpha 0.5
-subplot 4 4 11:rotate 40 60:box
-fall x y z 'g';meshnum 10:fall x y z 'rx';meshnum 10
-subplot 4 4 12:rotate 40 60:box:belt x y z '';meshnum 10;light on
-subplot 4 4 13:rotate 40 60:box:boxs x y z '';meshnum 10;light on
-subplot 4 4 14:rotate 40 60:box:boxs x y z '#';meshnum 10;light on
-subplot 4 4 15:rotate 40 60:box:boxs x y z '@';meshnum 10;light on
-
new x 50 50 50 '(x+2)/3*sin(pi*y/2)'
-new y 50 50 50 '(x+2)/3*cos(pi*y/2)'
-new z 50 50 50 'z'
-new c 50 50 50 '-2*(x^2+y^2+z^4-z^2)+0.2'
-new d 50 50 50 '1-2*tanh(2*(x+y)^2)'
-
-alpha on:light on
-subplot 4 3 0:rotate 40 60:box:surf3 x y z c
-subplot 4 3 1:rotate 40 60:box:surf3c x y z c d
-subplot 4 3 2:rotate 40 60:box:surf3a x y z c d
-subplot 4 3 3:rotate 40 60:box:cloud x y z c
-subplot 4 3 4:rotate 40 60:box:cont3 x y z c:cont3 x y z c 'x':cont3 x y z c 'z'
-subplot 4 3 5:rotate 40 60:box:contf3 x y z c:contf3 x y z c 'x':contf3 x y z c 'z'
-subplot 4 3 6:rotate 40 60:box:dens3 x y z c:dens3 x y z c 'x':dens3 x y z c 'z'
-subplot 4 3 7:rotate 40 60:box:dots x y z c;meshnum 15
-subplot 4 3 8:rotate 40 60:box:densx c '' 0:densy c '' 0:densz c '' 0
-subplot 4 3 9:rotate 40 60:box:contx c '' 0:conty c '' 0:contz c '' 0
-subplot 4 3 10:rotate 40 60:box:contfx c '' 0:contfy c '' 0:contfz c '' 0
-
new x 20 20 20 '(x+2)/3*sin(pi*y/2)'
-new y 20 20 20 '(x+2)/3*cos(pi*y/2)'
-new z 20 20 20 'z+x'
-new ex 20 20 20 'x'
-new ey 20 20 20 'x^2+y'
-new ez 20 20 20 'y^2+z'
-
-new x1 50 50 '(x+2)/3*sin(pi*y/2)'
-new y1 50 50 '(x+2)/3*cos(pi*y/2)'
-new e1 50 50 'x'
-new e2 50 50 'x^2+y'
-
-subplot 3 3 0:rotate 40 60:box:vect x1 y1 e1 e2
-subplot 3 3 1:rotate 40 60:box:flow x1 y1 e1 e2
-subplot 3 3 2:rotate 40 60:box:pipe x1 y1 e1 e2
-subplot 3 3 3:rotate 40 60:box:dew x1 y1 e1 e2
-subplot 3 3 4:rotate 40 60:box:vect x y z ex ey ez
-subplot 3 3 5:rotate 40 60:box
-vect3 x y z ex ey ez:vect3 x y z ex ey ez 'x':vect3 x y z ex ey ez 'z'
-grid3 x y z z '{r9}':grid3 x y z z '{g9}x':grid3 x y z z '{b9}z'
-subplot 3 3 6:rotate 40 60:box:flow x y z ex ey ez
-subplot 3 3 7:rotate 40 60:box:pipe x y z ex ey ez
-
new re 128 'exp(-48*(x+0.7)^2)':new im 128
-pde a 'p^2+q^2-x-1+i*0.5*(z+x)*(z>-x)' re im 0.01 30
-transpose a
-subplot 1 1 0 '<_':title 'PDE solver'
-axis:xlabel '\i x':ylabel '\i z'
-crange 0 1:dens a 'wyrRk'
-fplot '-x' 'k|'
-text 0 0.95 'Equation: ik_0\partial_zu + \Delta u + x\cdot u + i \frac{x+z}{2}\cdot u = 0\n{}absorption: (x+z)/2 for x+z>0'
-
Function pipe is similar to flow but draw pipes (tubes) which radius is proportional to the amplitude of vector field. The color scheme is used for coloring (see Color scheme). At this warm color corresponds to normal flow (like attractor), cold one corresponds to inverse flow (like source).
-
-
MGL code:
-
call 'prepare2v'
-call 'prepare3v'
-subplot 2 2 0 '':title 'Pipe plot (default)':light on:box:pipe a b
-subplot 2 2 1 '':title '"i" style':box:pipe a b 'i'
-subplot 2 2 2 '':title 'from edges only':box:pipe a b '#'
-subplot 2 2 3:title '3d variant':rotate 50 60:box:pipe ex ey ez '' 0.1
-
Function plot is most standard way to visualize 1D data array. By default, Plot use colors from palette. However, you can specify manual color/palette, and even set to use new color for each points by using `!` style. Another feature is `` style which draw only markers without line between points.
-
Function pmap draw Poincare map - show intersections of the curve and the surface.
-
-
MGL code:
-
subplot 1 1 0 '<_^':title 'Poincare map sample'
-ode r 'cos(y)+sin(z);cos(z)+sin(x);cos(x)+sin(y)' 'xyz' [0.1,0,0] 0.1 100
-rotate 40 60:copy x r(0):copy y r(1):copy z r(2)
-ranges x y z
-axis:plot x y z 'b'
-xlabel '\i x' 0:ylabel '\i y' 0:zlabel '\i z'
-pmap x y z z 'b#o'
-fsurf '0'
-
ranges 0 1 0 1 0 1
-new x 50 '0.25*(1+cos(2*pi*x))'
-new y 50 '0.25*(1+sin(2*pi*x))'
-new z 50 'x'
-new a 20 30 '30*x*y*(1-x-y)^2*(x+y<1)'
-new rx 10 'rnd':new ry 10:fill ry '(1-v)*rnd' rx
-light on
-
-title 'Projection sample':ternary 4:rotate 50 60
-box:axis:grid
-plot x y z 'r2':surf a '#'
-xlabel 'X':ylabel 'Y':zlabel 'Z'
-
The radar plot is variant of plot, which make plot in polar coordinates and draw radial rays in point directions. If you just need a plot in polar coordinates then I recommend to use Curvilinear coordinates or plot in parametric form with x=r*cos(fi); y=r*sin(fi);.
-
-
MGL code:
-
new yr 10 3 '0.4*sin(pi*(x+1.5+y/2)+0.1*rnd)'
-subplot 1 1 0 '':title 'Radar plot (with grid, "\#")':radar yr '#'
-
new x 10 '0.5+rnd':cumsum x 'x':norm x -1 1
-copy y sin(pi*x)/1.5
-subplot 2 2 0 '<_':title 'Refill sample'
-box:axis:plot x y 'o ':fplot 'sin(pi*x)/1.5' 'B:'
-new r 100:refill r x y:plot r 'r'
-
-subplot 2 2 1 '<_':title 'Global spline'
-box:axis:plot x y 'o ':fplot 'sin(pi*x)/1.5' 'B:'
-new r 100:gspline r x y:plot r 'r'
-
-new y 10 '0.5+rnd':cumsum y 'x':norm y -1 1
-copy xx x:extend xx 10
-copy yy y:extend yy 10:transpose yy
-copy z sin(pi*xx*yy)/1.5
-alpha on:light on
-subplot 2 2 2:title '2d regular':rotate 40 60
-box:axis:mesh xx yy z 'k'
-new rr 100 100:refill rr x y z:surf rr
-
-new xx 10 10 '(x+1)/2*cos(y*pi/2-1)':new yy 10 10 '(x+1)/2*sin(y*pi/2-1)'
-copy z sin(pi*xx*yy)/1.5
-subplot 2 2 3:title '2d non-regular':rotate 40 60
-box:axis:plot xx yy z 'ko '
-new rr 100 100:refill rr xx yy z:surf rr
-
Function region fill the area between 2 curves. It support gradient filling if 2 colors per curve is specified. Also it can fill only the region y1<y<y2 if style `i` is used.
-
zrange 0 1
-new x 20 30 '(x+2)/3*cos(pi*y)'
-new y 20 30 '(x+2)/3*sin(pi*y)'
-new z 20 30 'exp(-6*x^2-2*sin(pi*y)^2)'
-
-subplot 2 1 0:title 'Cartesian space':rotate 30 -40
-axis 'xyzU':box
-xlabel 'x':ylabel 'y'
-origin 1 1:grid 'xy'
-mesh x y z
-
-# section along 'x' direction
-solve u x 0.5 'x'
-var v u.nx 0 1
-evaluate yy y u v
-evaluate xx x u v
-evaluate zz z u v
-plot xx yy zz 'k2o'
-
-# 1st section along 'y' direction
-solve u1 x -0.5 'y'
-var v1 u1.nx 0 1
-evaluate yy y v1 u1
-evaluate xx x v1 u1
-evaluate zz z v1 u1
-plot xx yy zz 'b2^'
-
-# 2nd section along 'y' direction
-solve u2 x -0.5 'y' u1
-evaluate yy y v1 u2
-evaluate xx x v1 u2
-evaluate zz z v1 u2
-plot xx yy zz 'r2v'
-
-subplot 2 1 1:title 'Accompanied space'
-ranges 0 1 0 1:origin 0 0
-axis:box:xlabel 'i':ylabel 'j':grid2 z 'h'
-
-plot u v 'k2o':line 0.4 0.5 0.8 0.5 'kA'
-plot v1 u1 'b2^':line 0.5 0.15 0.5 0.3 'bA'
-plot v1 u2 'r2v':line 0.5 0.7 0.5 0.85 'rA'
-
Function surf is most standard way to visualize 2D data array. Surf use color scheme for coloring (see Color scheme). You can use `#` style for drawing black meshes on the surface.
-
-
MGL code:
-
call 'prepare2d'
-subplot 2 2 0:title 'Surf plot (default)':rotate 50 60:light on:box:surf a
-subplot 2 2 1:title '"\#" style; meshnum 10':rotate 50 60:box:surf a '#'; meshnum 10
-subplot 2 2 2:title '"." style':rotate 50 60:box:surf a '.'
-new x 50 40 '0.8*sin(pi*x)*sin(pi*(y+1)/2)'
-new y 50 40 '0.8*cos(pi*x)*sin(pi*(y+1)/2)'
-new z 50 40 '0.8*cos(pi*(y+1)/2)'
-subplot 2 2 3:title 'parametric form':rotate 50 60:box:surf x y z 'BbwrR'
-
Function surf3 is one of most suitable (for my opinion) functions to visualize 3D data. It draw the isosurface(s) - surface(s) of constant amplitude (3D analogue of contour lines). You can draw wired isosurfaces if specify `#` style.
-
-
MGL code:
-
call 'prepare3d'
-light on:alpha on
-subplot 2 2 0:title 'Surf3 plot (default)'
-rotate 50 60:box:surf3 c
-subplot 2 2 1:title '"\#" style'
-rotate 50 60:box:surf3 c '#'
-subplot 2 2 2:title '"." style'
-rotate 50 60:box:surf3 c '.'
-
call 'prepare1d'
-subplot 1 3 0 '':box:plot y(:,0)
-text y 'This is very very long string drawn along a curve' 'k'
-text y 'Another string drawn under a curve' 'Tr'
-subplot 1 3 1 '':box:plot y(:,0)
-text y 'This is very very long string drawn along a curve' 'k:C'
-text y 'Another string drawn under a curve' 'Tr:C'
-subplot 1 3 2 '':box:plot y(:,0)
-text y 'This is very very long string drawn along a curve' 'k:R'
-text y 'Another string drawn under a curve' 'Tr:R'
-
Example of use triangulate for arbitrary placed points.
-
-
MGL code:
-
new x 100 '2*rnd-1':new y 100 '2*rnd-1':copy z x^2-y^2
-new g 30 30:triangulate d x y
-title 'Triangulation'
-rotate 50 60:box:light on
-triplot d x y z:triplot d x y z '#k'
-datagrid g x y z:mesh g 'm'
-
Functions triplot and quadplot draw set of triangles (or quadrangles, correspondingly) for irregular data arrays. Note, that you have to provide not only vertexes, but also the indexes of triangles or quadrangles. I.e. perform triangulation by some other library. See also triangulate.
-
Function vect is most standard way to visualize vector fields - it draw a lot of arrows or hachures for each data cell. It have a lot of options which can be seen on the figure (and in the sample code), and use color scheme for coloring (see Color scheme).
-
-
MGL code:
-
call 'prepare2v'
-call 'prepare3v'
-subplot 3 2 0 '':title 'Vect plot (default)':box:vect a b
-subplot 3 2 1 '':title '"." style; "=" style':box:vect a b '.='
-subplot 3 2 2 '':title '"f" style':box:vect a b 'f'
-subplot 3 2 3 '':title '">" style':box:vect a b '>'
-subplot 3 2 4 '':title '"<" style':box:vect a b '<'
-subplot 3 2 5:title '3d variant':rotate 50 60:box:vect ex ey ez
-
Function vect3 draw ordinary vector field plot but at slices of 3D data.
-
-
MGL code:
-
call 'prepare3v'
-subplot 2 1 0:title 'Vect3 sample':rotate 50 60
-origin 0 0 0:box:axis '_xyz'
-vect3 ex ey ez 'x':vect3 ex ey ez:vect3 ex ey ez 'z'
-subplot 2 1 1:title '"f" style':rotate 50 60
-origin 0 0 0:box:axis '_xyz'
-vect3 ex ey ez 'fx':vect3 ex ey ez 'f':vect3 ex ey ez 'fz'
-grid3 ex 'Wx':grid3 ex 'W':grid3 ex 'Wz'
-
list x -0.3 0 0.3:list y 0.3 -0.3 0.3:list e 0.7 0.7 0.7
-subplot 1 1 0:title 'Venn-like diagram'
-transptype 1:alpha on:error x y e e '!rgb@#o';alpha 0.1
-
This appendix contain the full list of symbols (characters) used by MathGL for setting up plot. Also it contain sections for full list of hot-keys supported by mglview tool and by UDAV program.
-
Create new window with empty script. Note, all scripts share variables. So, second window can be used to see some additional information of existed variables.
-
Ctrl-O
Open and execute/show script or data from file. You may switch off automatic exection in UDAV properties
-
Ctrl-S
Save script to a file.
-
Ctrl-P
Open printer dialog and print graphics.
-
Ctrl-Z
Undo changes in script editor.
-
Ctrl-Shift-Z
Redo changes in script editor.
-
Ctrl-X
Cut selected text into clipboard.
-
Ctrl-C
Copy selected text into clipboard.
-
Ctrl-V
Paste selected text from clipboard.
-
Ctrl-A
Select all text in editor.
-
Ctrl-F
Show dialog for text finding.
-
F3
Find next occurrence of the text.
-
Win-C or Meta-C
Show dialog for new command and put it into the script.
-
Win-F or Meta-F
Insert last fitted formula with found coefficients.
-
Win-S or Meta-S
Show dialog for styles and put it into the script. Styles define the plot view (color scheme, marks, dashing and so on).
-
Win-O or Meta-O
Show dialog for options and put it into the script. Options are used for additional setup the plot.
-
Win-N or Meta-N
Replace selected expression by its numerical value.
-
Win-P or Meta-P
Select file and insert its file name into the script.
-
Win-G or Meta-G
Show dialog for plot setup and put resulting code into the script. This dialog setup axis, labels, lighting and other general things.
-
Ctrl-Shift-O
Load data from file. Data will be deleted only at exit but UDAV will not ask to save it.
-
Ctrl-Shift-S
Save data to a file.
-
Ctrl-Shift-C
Copy range of numbers to clipboard.
-
Ctrl-Shift-V
Paste range of numbers from clipboard.
-
Ctrl-Shift-N
Recreate the data with new sizes and fill it by zeros.
-
Ctrl-Shift-R
Resize (interpolate) the data to specified sizes.
-
Ctrl-Shift-T
Transform data along dimension(s).
-
Ctrl-Shift-M
Make another data.
-
Ctrl-Shift-H
Find histogram of data.
-
Ctrl-T
Switch on/off transparency for the graphics.
-
Ctrl-L
Switch on/off additional lightning for the graphics.
-
Ctrl-G
Switch on/off grid of absolute coordinates.
-
Ctrl-Space
Restore default graphics rotation, zoom and perspective.
-
F5
Execute script and redraw graphics.
-
F6
Change canvas size to fill whole region.
-
F7
Stop script execution and drawing.
-
F8
Show/hide tool window with list of hidden plots.
-
F9
Restore status for `once` command and reload data.
-
Ctrl-F5
Run slideshow. If no parameter specified then the dialog with slideshow options will appear.
-
Ctrl-Comma, Ctrl-Period
Show next/previous slide. If no parameter specified then the dialog with slideshow options will appear.
-
Ctrl-W
Open dialog with slideshow options.
-
Ctrl-Shift-G
Copy graphics to clipboard.
-
F1
Show help on MGL commands
-
F2
Show/hide tool window with messages and information.
-
F4
Show/hide calculator which evaluate and help to type textual formulas. Textual formulas may contain data variables too.
The purpose of this License is to make a manual, textbook, or other
-functional and useful document free in the sense of freedom: to
-assure everyone the effective freedom to copy and redistribute it,
-with or without modifying it, either commercially or noncommercially.
-Secondarily, this License preserves for the author and publisher a way
-to get credit for their work, while not being considered responsible
-for modifications made by others.
-
-
This License is a kind of “copyleft”, which means that derivative
-works of the document must themselves be free in the same sense. It
-complements the GNU General Public License, which is a copyleft
-license designed for free software.
-
-
We have designed this License in order to use it for manuals for free
-software, because free software needs free documentation: a free
-program should come with manuals providing the same freedoms that the
-software does. But this License is not limited to software manuals;
-it can be used for any textual work, regardless of subject matter or
-whether it is published as a printed book. We recommend this License
-principally for works whose purpose is instruction or reference.
-
-
APPLICABILITY AND DEFINITIONS
-
-
This License applies to any manual or other work, in any medium, that
-contains a notice placed by the copyright holder saying it can be
-distributed under the terms of this License. Such a notice grants a
-world-wide, royalty-free license, unlimited in duration, to use that
-work under the conditions stated herein. The “Document”, below,
-refers to any such manual or work. Any member of the public is a
-licensee, and is addressed as “you”. You accept the license if you
-copy, modify or distribute the work in a way requiring permission
-under copyright law.
-
-
A “Modified Version” of the Document means any work containing the
-Document or a portion of it, either copied verbatim, or with
-modifications and/or translated into another language.
-
-
A “Secondary Section” is a named appendix or a front-matter section
-of the Document that deals exclusively with the relationship of the
-publishers or authors of the Document to the Document`s overall
-subject (or to related matters) and contains nothing that could fall
-directly within that overall subject. (Thus, if the Document is in
-part a textbook of mathematics, a Secondary Section may not explain
-any mathematics.) The relationship could be a matter of historical
-connection with the subject or with related matters, or of legal,
-commercial, philosophical, ethical or political position regarding
-them.
-
-
The “Invariant Sections” are certain Secondary Sections whose titles
-are designated, as being those of Invariant Sections, in the notice
-that says that the Document is released under this License. If a
-section does not fit the above definition of Secondary then it is not
-allowed to be designated as Invariant. The Document may contain zero
-Invariant Sections. If the Document does not identify any Invariant
-Sections then there are none.
-
-
The “Cover Texts” are certain short passages of text that are listed,
-as Front-Cover Texts or Back-Cover Texts, in the notice that says that
-the Document is released under this License. A Front-Cover Text may
-be at most 5 words, and a Back-Cover Text may be at most 25 words.
-
-
A “Transparent” copy of the Document means a machine-readable copy,
-represented in a format whose specification is available to the
-general public, that is suitable for revising the document
-straightforwardly with generic text editors or (for images composed of
-pixels) generic paint programs or (for drawings) some widely available
-drawing editor, and that is suitable for input to text formatters or
-for automatic translation to a variety of formats suitable for input
-to text formatters. A copy made in an otherwise Transparent file
-format whose markup, or absence of markup, has been arranged to thwart
-or discourage subsequent modification by readers is not Transparent.
-An image format is not Transparent if used for any substantial amount
-of text. A copy that is not “Transparent” is called “Opaque”.
-
-
Examples of suitable formats for Transparent copies include plain
-ASCII without markup, Texinfo input format, LaTeX input
-format, SGML or XML using a publicly available
-DTD, and standard-conforming simple HTML,
-PostScript or PDF designed for human modification. Examples
-of transparent image formats include PNG, XCF and
-JPG. Opaque formats include proprietary formats that can be
-read and edited only by proprietary word processors, SGML or
-XML for which the DTD and/or processing tools are
-not generally available, and the machine-generated HTML,
-PostScript or PDF produced by some word processors for
-output purposes only.
-
-
The “Title Page” means, for a printed book, the title page itself,
-plus such following pages as are needed to hold, legibly, the material
-this License requires to appear in the title page. For works in
-formats which do not have any title page as such, “Title Page” means
-the text near the most prominent appearance of the work`s title,
-preceding the beginning of the body of the text.
-
-
A section “Entitled XYZ” means a named subunit of the Document whose
-title either is precisely XYZ or contains XYZ in parentheses following
-text that translates XYZ in another language. (Here XYZ stands for a
-specific section name mentioned below, such as “Acknowledgements”,
-“Dedications”, “Endorsements”, or “History”.) To “Preserve the Title”
-of such a section when you modify the Document means that it remains a
-section “Entitled XYZ” according to this definition.
-
-
The Document may include Warranty Disclaimers next to the notice which
-states that this License applies to the Document. These Warranty
-Disclaimers are considered to be included by reference in this
-License, but only as regards disclaiming warranties: any other
-implication that these Warranty Disclaimers may have is void and has
-no effect on the meaning of this License.
-
-
VERBATIM COPYING
-
-
You may copy and distribute the Document in any medium, either
-commercially or noncommercially, provided that this License, the
-copyright notices, and the license notice saying this License applies
-to the Document are reproduced in all copies, and that you add no other
-conditions whatsoever to those of this License. You may not use
-technical measures to obstruct or control the reading or further
-copying of the copies you make or distribute. However, you may accept
-compensation in exchange for copies. If you distribute a large enough
-number of copies you must also follow the conditions in section 3.
-
-
You may also lend copies, under the same conditions stated above, and
-you may publicly display copies.
-
-
COPYING IN QUANTITY
-
-
If you publish printed copies (or copies in media that commonly have
-printed covers) of the Document, numbering more than 100, and the
-Document`s license notice requires Cover Texts, you must enclose the
-copies in covers that carry, clearly and legibly, all these Cover
-Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on
-the back cover. Both covers must also clearly and legibly identify
-you as the publisher of these copies. The front cover must present
-the full title with all words of the title equally prominent and
-visible. You may add other material on the covers in addition.
-Copying with changes limited to the covers, as long as they preserve
-the title of the Document and satisfy these conditions, can be treated
-as verbatim copying in other respects.
-
-
If the required texts for either cover are too voluminous to fit
-legibly, you should put the first ones listed (as many as fit
-reasonably) on the actual cover, and continue the rest onto adjacent
-pages.
-
-
If you publish or distribute Opaque copies of the Document numbering
-more than 100, you must either include a machine-readable Transparent
-copy along with each Opaque copy, or state in or with each Opaque copy
-a computer-network location from which the general network-using
-public has access to download using public-standard network protocols
-a complete Transparent copy of the Document, free of added material.
-If you use the latter option, you must take reasonably prudent steps,
-when you begin distribution of Opaque copies in quantity, to ensure
-that this Transparent copy will remain thus accessible at the stated
-location until at least one year after the last time you distribute an
-Opaque copy (directly or through your agents or retailers) of that
-edition to the public.
-
-
It is requested, but not required, that you contact the authors of the
-Document well before redistributing any large number of copies, to give
-them a chance to provide you with an updated version of the Document.
-
-
MODIFICATIONS
-
-
You may copy and distribute a Modified Version of the Document under
-the conditions of sections 2 and 3 above, provided that you release
-the Modified Version under precisely this License, with the Modified
-Version filling the role of the Document, thus licensing distribution
-and modification of the Modified Version to whoever possesses a copy
-of it. In addition, you must do these things in the Modified Version:
-
-
-
Use in the Title Page (and on the covers, if any) a title distinct
-from that of the Document, and from those of previous versions
-(which should, if there were any, be listed in the History section
-of the Document). You may use the same title as a previous version
-if the original publisher of that version gives permission.
-
-
List on the Title Page, as authors, one or more persons or entities
-responsible for authorship of the modifications in the Modified
-Version, together with at least five of the principal authors of the
-Document (all of its principal authors, if it has fewer than five),
-unless they release you from this requirement.
-
-
State on the Title page the name of the publisher of the
-Modified Version, as the publisher.
-
-
Preserve all the copyright notices of the Document.
-
-
Add an appropriate copyright notice for your modifications
-adjacent to the other copyright notices.
-
-
Include, immediately after the copyright notices, a license notice
-giving the public permission to use the Modified Version under the
-terms of this License, in the form shown in the Addendum below.
-
-
Preserve in that license notice the full lists of Invariant Sections
-and required Cover Texts given in the Document`s license notice.
-
-
Include an unaltered copy of this License.
-
-
Preserve the section Entitled “History”, Preserve its Title, and add
-to it an item stating at least the title, year, new authors, and
-publisher of the Modified Version as given on the Title Page. If
-there is no section Entitled “History” in the Document, create one
-stating the title, year, authors, and publisher of the Document as
-given on its Title Page, then add an item describing the Modified
-Version as stated in the previous sentence.
-
-
Preserve the network location, if any, given in the Document for
-public access to a Transparent copy of the Document, and likewise
-the network locations given in the Document for previous versions
-it was based on. These may be placed in the “History” section.
-You may omit a network location for a work that was published at
-least four years before the Document itself, or if the original
-publisher of the version it refers to gives permission.
-
-
For any section Entitled “Acknowledgements” or “Dedications”, Preserve
-the Title of the section, and preserve in the section all the
-substance and tone of each of the contributor acknowledgements and/or
-dedications given therein.
-
-
Preserve all the Invariant Sections of the Document,
-unaltered in their text and in their titles. Section numbers
-or the equivalent are not considered part of the section titles.
-
-
Delete any section Entitled “Endorsements”. Such a section
-may not be included in the Modified Version.
-
-
Do not retitle any existing section to be Entitled “Endorsements” or
-to conflict in title with any Invariant Section.
-
-
Preserve any Warranty Disclaimers.
-
-
-
If the Modified Version includes new front-matter sections or
-appendices that qualify as Secondary Sections and contain no material
-copied from the Document, you may at your option designate some or all
-of these sections as invariant. To do this, add their titles to the
-list of Invariant Sections in the Modified Version`s license notice.
-These titles must be distinct from any other section titles.
-
-
You may add a section Entitled “Endorsements”, provided it contains
-nothing but endorsements of your Modified Version by various
-parties—for example, statements of peer review or that the text has
-been approved by an organization as the authoritative definition of a
-standard.
-
-
You may add a passage of up to five words as a Front-Cover Text, and a
-passage of up to 25 words as a Back-Cover Text, to the end of the list
-of Cover Texts in the Modified Version. Only one passage of
-Front-Cover Text and one of Back-Cover Text may be added by (or
-through arrangements made by) any one entity. If the Document already
-includes a cover text for the same cover, previously added by you or
-by arrangement made by the same entity you are acting on behalf of,
-you may not add another; but you may replace the old one, on explicit
-permission from the previous publisher that added the old one.
-
-
The author(s) and publisher(s) of the Document do not by this License
-give permission to use their names for publicity for or to assert or
-imply endorsement of any Modified Version.
-
-
COMBINING DOCUMENTS
-
-
You may combine the Document with other documents released under this
-License, under the terms defined in section 4 above for modified
-versions, provided that you include in the combination all of the
-Invariant Sections of all of the original documents, unmodified, and
-list them all as Invariant Sections of your combined work in its
-license notice, and that you preserve all their Warranty Disclaimers.
-
-
The combined work need only contain one copy of this License, and
-multiple identical Invariant Sections may be replaced with a single
-copy. If there are multiple Invariant Sections with the same name but
-different contents, make the title of each such section unique by
-adding at the end of it, in parentheses, the name of the original
-author or publisher of that section if known, or else a unique number.
-Make the same adjustment to the section titles in the list of
-Invariant Sections in the license notice of the combined work.
-
-
In the combination, you must combine any sections Entitled “History”
-in the various original documents, forming one section Entitled
-“History”; likewise combine any sections Entitled “Acknowledgements”,
-and any sections Entitled “Dedications”. You must delete all
-sections Entitled “Endorsements.”
-
-
COLLECTIONS OF DOCUMENTS
-
-
You may make a collection consisting of the Document and other documents
-released under this License, and replace the individual copies of this
-License in the various documents with a single copy that is included in
-the collection, provided that you follow the rules of this License for
-verbatim copying of each of the documents in all other respects.
-
-
You may extract a single document from such a collection, and distribute
-it individually under this License, provided you insert a copy of this
-License into the extracted document, and follow this License in all
-other respects regarding verbatim copying of that document.
-
-
AGGREGATION WITH INDEPENDENT WORKS
-
-
A compilation of the Document or its derivatives with other separate
-and independent documents or works, in or on a volume of a storage or
-distribution medium, is called an “aggregate” if the copyright
-resulting from the compilation is not used to limit the legal rights
-of the compilation`s users beyond what the individual works permit.
-When the Document is included in an aggregate, this License does not
-apply to the other works in the aggregate which are not themselves
-derivative works of the Document.
-
-
If the Cover Text requirement of section 3 is applicable to these
-copies of the Document, then if the Document is less than one half of
-the entire aggregate, the Document`s Cover Texts may be placed on
-covers that bracket the Document within the aggregate, or the
-electronic equivalent of covers if the Document is in electronic form.
-Otherwise they must appear on printed covers that bracket the whole
-aggregate.
-
-
TRANSLATION
-
-
Translation is considered a kind of modification, so you may
-distribute translations of the Document under the terms of section 4.
-Replacing Invariant Sections with translations requires special
-permission from their copyright holders, but you may include
-translations of some or all Invariant Sections in addition to the
-original versions of these Invariant Sections. You may include a
-translation of this License, and all the license notices in the
-Document, and any Warranty Disclaimers, provided that you also include
-the original English version of this License and the original versions
-of those notices and disclaimers. In case of a disagreement between
-the translation and the original version of this License or a notice
-or disclaimer, the original version will prevail.
-
-
If a section in the Document is Entitled “Acknowledgements”,
-“Dedications”, or “History”, the requirement (section 4) to Preserve
-its Title (section 1) will typically require changing the actual
-title.
-
-
TERMINATION
-
-
You may not copy, modify, sublicense, or distribute the Document except
-as expressly provided for under this License. Any other attempt to
-copy, modify, sublicense or distribute the Document is void, and will
-automatically terminate your rights under this License. However,
-parties who have received copies, or rights, from you under this
-License will not have their licenses terminated so long as such
-parties remain in full compliance.
-
-
FUTURE REVISIONS OF THIS LICENSE
-
-
The Free Software Foundation may publish new, revised versions
-of the GNU Free Documentation License from time to time. Such new
-versions will be similar in spirit to the present version, but may
-differ in detail to address new problems or concerns. See
-http://www.gnu.org/copyleft/.
-
-
Each version of the License is given a distinguishing version number.
-If the Document specifies that a particular numbered version of this
-License “or any later version” applies to it, you have the option of
-following the terms and conditions either of that specified version or
-of any later version that has been published (not as a draft) by the
-Free Software Foundation. If the Document does not specify a version
-number of this License, you may choose any version ever published (not
-as a draft) by the Free Software Foundation.
-
-
-
-
ADDENDUM: How to use this License for your documents
-
-
To use this License in a document you have written, include a copy of
-the License in the document and put the following copyright and
-license notices just after the title page:
-
-
-
Copyright (C) yearyour name.
- Permission is granted to copy, distribute and/or modify this document
- under the terms of the GNU Free Documentation License, Version 1.2
- or any later version published by the Free Software Foundation;
- with no Invariant Sections, no Front-Cover Texts, and no Back-Cover
- Texts. A copy of the license is included in the section entitled ``GNU
- Free Documentation License''.
-
-
-
If you have Invariant Sections, Front-Cover Texts and Back-Cover Texts,
-replace the “with…Texts.” line with this:
-
-
-
with the Invariant Sections being list their titles, with
- the Front-Cover Texts being list, and with the Back-Cover Texts
- being list.
-
-
-
If you have Invariant Sections without Cover Texts, or some other
-combination of the three, merge those two alternatives to suit the
-situation.
-
-
If your document contains nontrivial examples of program code, we
-recommend releasing these examples in parallel under your choice of
-free software license, such as the GNU General Public License,
-to permit their use in free software.
-